我基本上是在尝试制作标签以做出react,但存在一些问题。
这是文件 page.jsx
<RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
当您单击按钮 A 时, RadioGroup 组件需要取消选择按钮 B。
“选定”仅表示来自状态或属性的类名
这是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并不重要,它有一个触发原生 DOMonChange事件的常规 HTML 单选按钮
预期流量为:
- 单击按钮“A”
- 按钮“A”触发 onChange,原生 DOM 事件,它向上冒泡到 RadioGroup
- RadioGroup onChange 监听器被调用
- RadioGroup 需要取消选择按钮 B。这是我的问题。
这是我遇到的主要问题:我不能将<Button>s 移入RadioGroup,因为它的结构使得孩子是任意的。也就是说,标记可以是
<RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
或者
<RadioGroup>
<OtherThing title="A" />
<OtherThing title="B" />
</RadioGroup>
我已经尝试了几件事。
尝试: InRadioGroup的 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(...)
尝试: InRadioGroup的 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:使用 react-addons.js cloneWithProps方法在渲染时克隆子项,RadioGroup以便能够传递它们的属性
糟糕的解决方案#2:围绕 HTML/JSX 实现抽象,以便我可以动态传递属性(杀了我):
<RadioGroup items=[
{ type: Button, title: 'A' },
{ type: Button, title: 'B' }
]; />
然后在RadioGroup动态构建这些按钮。
这个问题对我没有帮助,因为我需要在不知道他们是什么的情况下渲染我的孩子