小编典典

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

reactjs

我本质上是在尝试做出回应,但是有一些问题。

这是档案 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”触发本地DOM事件onChange,该事件一直持续到RadioGroup
  • 调用RadioGroup onChange侦听器
  • RadioGroup中需要去选择按钮B 。这是我的问题。

这是我遇到的主要问题:我 无法<Button>进入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动态建立这些按钮。

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


阅读 261

收藏
2020-07-22

共1个答案

小编典典

我不确定为什么您说使用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演示它的运行情况。

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

2020-07-22