首页 文章

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

提问于
浏览
85

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

这是文件 page.jsx

<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>

When you click on button A, the RadioGroup component needs to de-select button B .

“Selected”只是指来自州或 property 的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单选按钮,可触发本机DOM onChange 事件

The expected flow is:

  • 点击按钮"A"

  • Button "A"触发onChange,本机DOM事件,它会冒泡到RadioGroup

  • 调用RadioGroup onChange侦听器

  • RadioGroup needs to de-select button B . 这是我的问题 .

这里's the main problem I' m遇到:我 cannot move <Button>s into RadioGroup ,因为这个结构就是这样的孩子 arbitrary . 也就是说,标记可能是

<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>

要么

<RadioGroup>
    <OtherThing title="A" />
    <OtherThing title="B" />
</RadioGroup>

I've tried a few things.

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

});

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:RadioGroup 的onChange处理程序中:

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

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

});

Problem: 没有任何反应,即使我给 Button 类一个 componentWillReceiveProps 方法


Attempt: 我试图将父级的某些特定状态传递给子级,因此我可以更新父级状态并让子级自动响应 . 在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 :使用react-addons.js cloneWithProps方法在 RadioGroup 中的渲染时克隆子项,以便能够传递它们属性

Bad solution #2 :围绕HTML / JSX实现抽象,以便我可以动态传递属性(杀了我):

<RadioGroup items=[
    { type: Button, title: 'A' },
    { type: Button, title: 'B' }
]; />

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

This question对我没有帮助,因为我需要让我的孩子不知道他们是什么

3 回答

  • 5

    我不确定为什么你说使用 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);
    

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

    EDIT :这是一个包含动态标签内容的更完整示例:jsFiddle

  • 15

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

  • 37

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

    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>
      );
    });
    

    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>);
        }
    
    });
    

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

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

相关问题