最佳答案
我本质上是在试图制作标签作为回应,但有一些问题。
这是 page.jsx
文件
<RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
当您单击按钮 A 时,RadioGroup 组件需要取消选择按钮 B 。
“ Selected”只是指来自某个状态或属性的 className
这里是 RadioGroup.jsx
:
module.exports = React.createClass({
onChange: function( e ) {
// How to modify children properties here???
},
render: function() {
return (<div onChange={this.onChange}>
{this.props.children}
</div>);
}
});
Button.jsx
的来源并不重要,它有一个常规的 HTML 单选按钮,可以触发本机 DOMonChange
事件
预期流量为:
下面是我遇到的主要问题: I 不能将 ABC0移动到 RadioGroup
,因为这个结构的子节点是 随心所欲。也就是说,标记可能是
<RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
或者
<RadioGroup>
<OtherThing title="A" />
<OtherThing title="B" />
</RadioGroup>
我试过几种方法。
尝试: 在 RadioGroup
的 onChange 处理程序中:
React.Children.forEach( this.props.children, function( child ) {
// Set the selected state of each child to be if the underlying <input>
// value matches the child's value
child.setState({ selected: child.props.value === e.target.value });
});
问题:
Invalid access to component property "setState" on exports at the top
level. See react-warning-descriptors . Use a static method
instead: <exports />.type.setState(...)
尝试: 在 RadioGroup
的 onChange 处理程序中:
React.Children.forEach( this.props.children, function( child ) {
child.props.selected = child.props.value === e.target.value;
});
问题: 什么都没有发生,即使我给 Button
类一个 componentWillReceiveProps
方法
尝试: 我尝试将父级的一些特定状态传递给子级,这样我就可以更新父级状态并让子级自动响应。在 RadioGroup 的渲染功能中:
React.Children.forEach( this.props.children, function( item ) {
this.transferPropsTo( item );
}, this);
问题:
Failed to make request: Error: Invariant Violation: exports: You can't call
transferPropsTo() on a component that you don't own, exports. This usually
means you are calling transferPropsTo() on a component passed in as props
or children.
糟糕的解决方案 # 1 : 使用 response-addons。JsCloneWithProps方法在 RadioGroup
中的呈现时克隆子元素,以便能够传递它们的属性
糟糕的解决方案 # 2 : 围绕 HTML/JSX 实现一个抽象,这样我就可以动态地传递属性(杀了我) :
<RadioGroup items=[
{ type: Button, title: 'A' },
{ type: Button, title: 'B' }
]; />
然后在 RadioGroup
中动态构建这些按钮。