【问题标题】:Updating child's state from parent component从父组件更新子组件的状态
【发布时间】:2017-09-28 19:57:41
【问题描述】:

假设我的父组件有两个子组件:

Parent
| Child1
| Child2

我从 Child2 获得输入并将其传递给 Parent 组件(直到现在,我知道该怎么做)。但是我需要将该输入传递给 Child1 以更新它的状态。

我该怎么做?

【问题讨论】:

  • 问题解决了吗?

标签: javascript reactjs


【解决方案1】:

**组件父级**

   import React from 'react';
    import MM from './modall';
    class App extends React.Component {
        constructor() {
            super();
            this.state = {
                naslov:'',
                telo:''
            };
            this.setStateHandler = this.setStateHandler.bind(this);
            this.postaviStanje = this.postaviStanje.bind(this);
            this.Stanje = this.Stanje.bind(this);
        }
        setStateHandler() {
            this.setState({ naslov: "Naslov Prvi u Modalu", telo:"Novo Prvo telo modala"});

        };
        postaviStanje(){
          this.setState({naslov: " Novi drugi u Modalu", telo:"Novo drugo  telo modala"});
        };
        Stanje(){
          this.setState({naslov: " Novi treci u Modalu", telo:"Novo trece  telo modala"});

        };
        render() {
            return (
                <div>
                    <button onClick = {this.setStateHandler} data-toggle="modal" data-target="#modal">SET STATE</button>
                    <button onClick = {this.postaviStanje} data-toggle="modal" data-target="#modal">SET STATE2</button>
                    <button onClick = {this.Stanje} data-toggle="modal" data-target="#modal">SET STATE3</button>
                    <MM telo={this.state.telo} naslov={this.state.naslov} />)

                </div>
            );
        }
    }
    export default App;

子项

 /**
     * Created by trika on 31-Jan-18.
     */
    import React,{Component} from 'react';

    class Modal extends Component{
        constructor(props) {
            super(props);
            this.state = {
                naslov:this.props.naslov,
                telo: this.props.telo
            };
        }

        render(){

            return(
                <div className="modal" id="modal" role="dialog">
                    <div className="modal-dialog" role="document">
                        <div className="modal-content">
                            <div className="modal-header">
                                <h1 className="modal-title"><strong>{this.props.naslov}</strong></h1>
                                <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div className="modal-body">
                                <p>Modal body text goes here.</p>
                                <h2><strong>{this.props.telo}</strong></h2>
                            </div>
                            <div className="modal-footer">
                                <button type="button" className="btn btn-primary">Save changes</button>
                                <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            );
        }
    }

    export default Modal;

【讨论】:

    【解决方案2】:

    希望您能理解主要思想 - 在 Parent 组件中创建一个函数,该函数将更改传递给 Child1 的值。 ReactJS: Why is passing the component initial state a prop an anti-pattern?

    class Parent extends Component {
      constructor(props){
        super(props);
        this.state = {
          value: ""
        }
      }
      changeValue(value){
        this.setState({value});
      }
      render(){
        return (
          <div>
              <Child1 value={this.state.value}/>
              <Child2 changeValue={changeValue}/>
          </div>
        )
      }
    }
    
    
    class Child2 extends Component {
      constructor(props) {
        super(props);
        this.state={
          input: ""
        }
      }
      handleChange(e){
        var {value} = e.target;
        this.setState({
          input: value
        },() => this.props.changeValue(value));
      }
      render(){
        return (
          <div>
              <input value={this.state.input} onChange={this.handleChange}/>
          </div>
        )
      }
    }
    
    
    
    class Child1 extends Component {
    
      constructor(props) {
        super(props);
        this.state={value:''}
      }
      componentWillReceiveProps(nextProps) {
        this.setState({value: nextProps.value})
      }
    
    
      render(){
        return (
          <div>
              {this.props.value}
          </div>
        )
      }
    }
    

    【讨论】:

    • 谢谢,但我认为这不起作用,您正在将道具传递给您的 Child1,但我想要更新它的状态(您的 Child1 没有任何状态值)。跨度>
    • 好的,它有一个状态。但是 - 它被认为是反模式 - 从道具更新你的状态。
    • 谢谢,但是否可以在不声明父组件状态的情况下做到这一点?就像通过父组件将它从 Child2“直接”传递给 Child1(我希望你明白我的意思)。因为实际上我想将 Child2 的输入传递给 Child1 的孩子的孩子......我认为通过向每个孩子声明一个状态只是为了通过孩子传递信息而不必要地占用内存。
    • 我猜 - 不!否则使用 Redux 之类的东西。
    • 是的,我也在考虑 Redux。感谢您的帮助。
    【解决方案3】:

    您可以在子组件中拥有一个函数,该函数根据父组件发送的值更新状态。您可以使用refs访问父组件的子组件的功能

    例子

    家长:

    class Parent extends React.Component {
         funcUpdateChild1 = () => {
              this.child1.updateState('value here');
         }
         render() {
              return (
                  <Child1 ref={(ip) => {this.child1 = ip}} />
                  <Child2 ref={(ip) => {this.child2 = ip}} />
             ) 
         }
    }
    

    孩子1

    class Child1 extends React.Component {
         updateState = (value) => {
             //use the value to set state here
         }
         render() {
              return (
                  //child1 contents here
             ) 
         }
    }
    

    【讨论】:

    • 你有没有改变来尝试这种方法
    • 我不明白 ref={(ip) => {this.child1 = ip} 应该在这里做什么,你能解释一下吗?
    • 那是声明refs的回调方式,
    • 您能否在您的代码中提供有关 Child2 和 Child1 中 ref 部分的更多详细信息?我也不明白您为什么要为 Child1 使用 ref,因为您正在通过 funcUpdateChild1 更新它的状态。
    • 您可以在此处阅读有关 refs 的信息:facebook.github.io/react/docs/refs-and-the-dom.html。您还需要 refs,因为您需要访问子组件中的函数
    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 2017-02-26
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2019-06-03
    • 2021-03-02
    • 2021-04-02
    相关资源
    最近更新 更多