Reactjs:如何从父级修改动态子组件状态或道具?

And*_*Ray 88 reactjs

我本质上是试图做出反应,但有一些问题.

这是文件 page.jsx

<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>
Run Code Online (Sandbox Code Playgroud)

当你点击按钮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>);
    }

});
Run Code Online (Sandbox Code Playgroud)

它的来源Button.jsx并不重要,它有一个常规的HTML单选按钮,可以触发本机DOM onChange事件

预期的流程是:

  • 点击按钮"A"
  • 按钮"A"触发onChange,本机DOM事件,它会冒泡到RadioGroup
  • 调用RadioGroup onChange侦听器
  • RadioGroup中需要去选择按钮B.这是我的问题.

这是我遇到的主要问题:我无法<Button>进入RadioGroup,因为这种结构使得孩子们是任意的.也就是说,标记可能是

<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>
Run Code Online (Sandbox Code Playgroud)

要么

<RadioGroup>
    <OtherThing title="A" />
    <OtherThing title="B" />
</RadioGroup>
Run Code Online (Sandbox Code Playgroud)

我尝试了一些事情.

尝试: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 });

});
Run Code Online (Sandbox Code Playgroud)

问题:

Invalid access to component property "setState" on exports at the top
level. See react-warning-descriptors . Use a static method
instead: <exports />.type.setState(...)
Run Code Online (Sandbox Code Playgroud)

尝试:RadioGroup'onChange处理程序中:

React.Children.forEach( this.props.children, function( child ) {

    child.props.selected = child.props.value === e.target.value;

});
Run Code Online (Sandbox Code Playgroud)

问题:没有任何事情发生,即使我给这个Button班级一个componentWillReceiveProps方法


尝试:我试图将父级的某个特定状态传递给子级,因此我可以更新父级状态并让子级自动响应.在RadioGroup的渲染功能中:

React.Children.forEach( this.props.children, function( item ) {
    this.transferPropsTo( item );
}, this);
Run Code Online (Sandbox Code Playgroud)

问题:

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.
Run Code Online (Sandbox Code Playgroud)

错误的解决方案#1:使用react-addons.js cloneWithProps方法在渲染时克隆子项RadioGroup以便能够传递它们属性

糟糕的解决方案#2:围绕HTML/JSX实现抽象,以便我可以动态传递属性(杀了我):

<RadioGroup items=[
    { type: Button, title: 'A' },
    { type: Button, title: 'B' }
]; />
Run Code Online (Sandbox Code Playgroud)

然后RadioGroup动态构建这些按钮.

这个问题对我没有帮助,因为我需要让我的孩子不知道他们是什么

Cla*_*urt 40

我不确定为什么你说使用cloneWithProps是一个糟糕的解决方案,但这是一个使用它的工作示例.

var Hello = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});

var App = React.createClass({
    render: function() {
        return (
            <Group ref="buttonGroup">
                <Button key={1} name="Component A"/>
                <Button key={2} name="Component B"/>
                <Button key={3} name="Component C"/>
            </Group>
        );
    }
});

var Group = React.createClass({
    getInitialState: function() {
        return {
            selectedItem: null
        };
    },

    selectItem: function(item) {
        this.setState({
            selectedItem: item
        });
    },

    render: function() {
        var selectedKey = (this.state.selectedItem && this.state.selectedItem.props.key) || null;
        var children = this.props.children.map(function(item, i) {
            var isSelected = item.props.key === selectedKey;
            return React.addons.cloneWithProps(item, {
                isSelected: isSelected,
                selectItem: this.selectItem,
                key: item.props.key
            });
        }, this);

        return (
            <div>
                <strong>Selected:</strong> {this.state.selectedItem ? this.state.selectedItem.props.name : 'None'}
                <hr/>
                {children}
            </div>
        );
    }

});

var Button = React.createClass({
    handleClick: function() {
        this.props.selectItem(this);
    },

    render: function() {
        var selected = this.props.isSelected;
        return (
            <div
                onClick={this.handleClick}
                className={selected ? "selected" : ""}
            >
                {this.props.name} ({this.props.key}) {selected ? "<---" : ""}
            </div>
        );
    }

});


React.renderComponent(<App />, document.body);
Run Code Online (Sandbox Code Playgroud)

这是一个jsFiddle显示它在行动.

编辑:这是一个更完整的动态标签内容示例:jsFiddle

  • 注意:不推荐使用cloneWithProps.请改用React.cloneElement. (15认同)
  • 这是令人难以置信的复杂做D3/Jquery可以做的事情只是一个:不是选择器`this`.除了使用React之外,还有什么真正的优势吗? (7认同)

Ryg*_*ygu 17

按钮应该是无状态的.而不是显式更新按钮的属性,只需更新组自己的状态并重新渲染.然后,组的渲染方法应该在渲染按钮时查看其状态,并将"活动"(或某些东西)仅传递给活动按钮.


Dan*_*ani 6

也许我的是一个奇怪的解决方案,但为什么不使用观察者模式?

RadioGroup.jsx

module.exports = React.createClass({
buttonSetters: [],
regSetter: function(v){
   buttonSetters.push(v);
},
handleChange: function(e) {
   // ...
   var name = e.target.name; //or name
   this.buttonSetters.forEach(function(v){
      if(v.name != name) v.setState(false);
   });
},
render: function() {
  return (
    <div>
      <Button title="A" regSetter={this.regSetter} onChange={handleChange}/>
      <Button title="B" regSetter={this.regSetter} onChange={handleChange} />
    </div>
  );
});
Run Code Online (Sandbox Code Playgroud)

Button.jsx

module.exports = React.createClass({

    onChange: function( e ) {
        // How to modify children properties here???
    },
    componentDidMount: function() {
         this.props.regSetter({name:this.props.title,setState:this.setState});
    },
    onChange:function() {
         this.props.onChange();
    },
    render: function() {
        return (<div onChange={this.onChange}>
            <input element .../>
        </div>);
    }

});
Run Code Online (Sandbox Code Playgroud)

也许你需要其他的东西,但我发现它非常强大,

我更喜欢使用外部模型,为各种任务提供观察者注册方法