Reactjs:如何从父级修改动态子组件状态或道具? [英] Reactjs: how to modify dynamic child component state or props from parent?

查看:66
本文介绍了Reactjs:如何从父级修改动态子组件状态或道具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在尝试制作标签,但有一些问题.

这里的文件 page.jsx

<按钮标题="A"/><按钮标题="B"/></RadioGroup>

当您点击按钮 A 时,RadioGroup 组件需要取消选择按钮 B.

Selected"仅表示来自状态或属性的类名

这是RadioGroup.jsx:

module.exports = React.createClass({onChange: 函数( e ) {//这里如何修改子属性???},渲染:函数(){return (<div onChange={this.onChange}>{this.props.children}

);}});

Button.jsx 的来源并不重要,它有一个普通的 HTML 单选按钮,可以触发原生 DOM onChange 事件

预期的流量是:

  • 点击按钮A"
  • 按钮A"触发 onChange,原生 DOM 事件,它向上冒泡到 RadioGroup
  • RadioGroup onChange 监听器被调用
  • RadioGroup 需要取消选择按钮 B.这是我的问题.

这是我遇到的主要问题:我无法将

);}});var Button = React.createClass({句柄点击:函数(){this.props.selectItem(this);},渲染:函数(){var selected = this.props.isSelected;返回 (

);}});React.renderComponent(, document.body);

这是一个 jsFiddle 展示了它的实际效果.

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

I'm essentially trying to make tabs in react, but with some issues.

Here's file 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" just means a className from a state or property

Here's 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>);
    }

});

The source of Button.jsx doesn't really matter, it has a regular HTML radio button that triggers the native DOM onChange event

The expected flow is:

  • Click on Button "A"
  • Button "A" triggers onChange, native DOM event, which bubbles up to RadioGroup
  • RadioGroup onChange listener is called
  • RadioGroup needs to de-select button B. This is my question.

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 am not sure why you say that using cloneWithProps is a bad solution, but here is a working example using it.

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

Here's a jsFiddle showing it in action.

EDIT: here's a more complete example with dynamic tab content : jsFiddle

这篇关于Reactjs:如何从父级修改动态子组件状态或道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆