我实质上是想让标签页做出反应,但是有一些问题。
这是档案 page.jsx
<RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
当你点击按钮A,在RadioGroup中组件需要去选择按钮B。
“选定”仅表示来自状态或属性的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
并不重要,它有一个触发原始DOM onChange
事件的常规HTML单选按钮
预期流量为:
- 点击按钮“ A”
- 按钮“ A”触发onChange,本机DOM事件,该事件一直持续到RadioGroup
- 调用RadioGroup onChange侦听器
- RadioGroup中需要去选择按钮B。这是我的问题。
Here's the main problem I'm encountering: I cannot move <Button>
s into RadioGroup
, because the structure of this is such that the children are arbitrary. That is, the markup could be
<RadioGroup>
<Button title="A" />
<Button title="B" />
</RadioGroup>
or
<RadioGroup>
<OtherThing title="A" />
<OtherThing title="B" />
</RadioGroup>
I've tried a few things.
Attempt: In RadioGroup
's onChange handler:
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 });
});
Problem:
Invalid access to component property "setState" on exports at the top
level. See react-warning-descriptors . Use a static method
instead: <exports />.type.setState(...)
Attempt: In RadioGroup
's onChange handler:
React.Children.forEach( this.props.children, function( child ) {
child.props.selected = child.props.value === e.target.value;
});
Problem: Nothing happens, even I give the Button
class a componentWillReceiveProps
method
Attempt: I attempted to pass some specific state of the parent to the children, so I can just update the parent state and have the children respond automatically. In the render function of RadioGroup:
React.Children.forEach( this.props.children, function( item ) {
this.transferPropsTo( item );
}, this);
Problem:
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.
Bad solution #1: Use react-addons.js cloneWithProps method to clone the children at render time in RadioGroup
to be able to pass them properties
Bad solution #2: Implement an abstraction around HTML / JSX so that I can pass in the properties dynamically (kill me):
<RadioGroup items=[
{ type: Button, title: 'A' },
{ type: Button, title: 'B' }
]; />
And then in RadioGroup
dynamically build these buttons.
This question doesn't help me because I need to render my children without knowing what they are
也许我的解决方案很奇怪,但是为什么不使用观察者模式呢?
也许您还需要其他东西,但是我发现它非常强大,
I really prefer to use an outer model that provide observer register methods for various tasks