首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Reactjs:如何从父组件修改动态子组件状态或道具?

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

Stack Overflow用户
提问于 2014-08-16 09:21:09
回答 4查看 92.7K关注 0票数 90

我本质上是想在react中创建标签,但有一些问题。

这是page.jsx文件

代码语言:javascript
复制
<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>

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

"Selected“只是指来自某个状态或属性的className

这是RadioGroup.jsx

代码语言:javascript
复制
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事件

预期流程为:

  • 点击按钮A
  • 按钮A触发onChange,本机DOM事件,其中冒泡到RadioGroup
  • RadioGroup onChange listener是called
  • RadioGroup需要取消选择按钮B
  • 。这是我的问题。

这是我遇到的主要问题:我不能将任意的<Button>**s移到** RadioGroup,中,因为它的结构是这样的:子对象是任意的。也就是说,标记可以是

代码语言:javascript
复制
<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>

代码语言:javascript
复制
<RadioGroup>
    <OtherThing title="A" />
    <OtherThing title="B" />
</RadioGroup>

:我已经尝试过很多东西了。

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

代码语言:javascript
复制
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 });

});

问题:

代码语言:javascript
复制
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处理程序中的

代码语言:javascript
复制
React.Children.forEach( this.props.children, function( child ) {

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

});

问题:没有发生任何事情,即使我给Button类一个componentWillReceiveProps方法也是如此

尝试:我尝试将父对象的某些特定状态传递给子对象,因此我可以只更新父对象的状态,并让子对象自动响应。在RadioGroup的render函数中:

代码语言:javascript
复制
React.Children.forEach( this.props.children, function( item ) {
    this.transferPropsTo( item );
}, this);

问题:

代码语言:javascript
复制
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实现一个抽象,这样我就可以动态地传递属性(杀了我吧):

代码语言:javascript
复制
<RadioGroup items=[
    { type: Button, title: 'A' },
    { type: Button, title: 'B' }
]; />

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

This question不能帮助我,因为我需要渲染我的孩子,而不知道他们是什么

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-08-17 10:57:30

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

代码语言:javascript
复制
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

票数 43
EN

Stack Overflow用户

发布于 2014-08-24 08:30:27

按钮应该是无状态的。不需要显式地更新按钮的属性,只需更新Group自己的状态并重新呈现即可。然后,Group的render方法应该在呈现按钮时查看其状态,并仅将" active“(或其他内容)传递给活动按钮。

票数 18
EN

Stack Overflow用户

发布于 2014-12-31 19:00:45

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

RadioGroup.jsx

代码语言:javascript
复制
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

代码语言:javascript
复制
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>);
    }

});

也许你需要别的东西,但我发现这很强大,

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25336124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档