【发布时间】:2014-10-09 18:17:20
【问题描述】:
我实际上是在尝试让标签页做出反应,但有一些问题。
这是文件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 的来源并不重要,它有一个常规的 HTML 单选按钮,可以触发原生 DOM 的 onChange 事件
预期流量为:
- 点击按钮“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>
我已经尝试了一些方法。
尝试:在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:使用 react-addons.js cloneWithProps 方法在 RadioGroup 的渲染时克隆子级,以便能够传递属性
糟糕的解决方案#2:围绕 HTML / JSX 实现一个抽象,以便我可以动态传递属性(杀了我):
<RadioGroup items=[
{ type: Button, title: 'A' },
{ type: Button, title: 'B' }
]; />
然后在RadioGroup 中动态构建这些按钮。
This question 对我没有帮助,因为我需要在不知道他们是什么的情况下渲染我的孩子
【问题讨论】:
-
如果孩子可以是任意的,那么
RadioGroup怎么可能知道它需要对其任意孩子的事件做出反应?它必须对它的孩子有所了解。 -
一般来说,如果你想修改不属于你的组件的属性,请使用
React.addons.cloneWithProps克隆它并传递你希望它拥有的新属性。props是不可变的,因此您正在创建一个新哈希,将其与当前道具合并,并将新哈希作为props传递给子组件的新实例。
标签: reactjs