簡體   English   中英

從父組件更新子狀態

[英]Updating child's state from parent component

假設我的父組件有兩個子組件:

Parent
| Child1
| Child2

我從 Child2 獲得輸入並將其傳遞給 Parent 組件(直到現在,我知道該怎么做)。 但是然后我需要將該輸入傳遞給 Child1 以更新它的狀態。

我怎樣才能做到這一點?

希望你能得到主要的想法 - 在Parent組件中創建一個函數,它將改變傳遞給Child1的值。 ReactJS:為什么將組件初始狀態傳遞給反模式?

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

您可以在子組件中具有一個函數,該函數根據父組件發送的值更新狀態。 您可以使用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}} />
         ) 
     }
}

Child1

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

**組件父母**

   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;

Compnent孩子

 /**
     * 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;

帶鈎子的現代解決方案:

1.父組件:

const Parent = ({}) => {
  const [child2Data, setChild2Data] = useState(null);
  
  return(
    <view>
      <Child1 child2Data={child2Data} />
      <Child2 setChild2Data={setChild2Data}/>
    </view>
  )
}

1. 孩子 2:

const Child2 = ({ setChild2Data }) => {
  const [data, setData] = useState(null);
  
  const _setData = (_data) => {
    setData(_data)
    setChild2Data(_data)
  }
  
  return(
    <view onClick={() => _setData("Any Data")}>
    </view>
  )
}

1. 孩子 1:

const Child1 = ({ child2Data }) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    setData(child2Data)
  }, [child2Data])
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM