如何将值发送给子组件,对其进行管理以及将结果返回给父组件

时间:2018-12-17 19:06:50

标签: reactjs

编辑。我问了一个问题,但是没有回答,所以人们知道我在问什么。因此,让我们输入一些代码。

父组件的关键部分:

constructor(props){
  super(props);
  ...
  this.state = {
    hourMinute: 1200
  }
}
.....
handleChange(hourMinute){
    this.setState({hourMinute: hourMinute});
}
.....
<HourMinute onChange={this.handleChange} hourMinute={this.state.hourMinute} />

子组件关键部分:

constructor(props){
    super(props);
    ....
    this.state = {
        hour: 5, // 0..24
        minute: 10, // 0..59
    }
}

static getDerivedStateFromProps(props, state) {
    const hourMinute = props.hourMinute;
    const hour = Math.floor(hourMinute/60);
    const minute = hourMinute - 60 * hour;

    return {
        hour: hour, // 0..24
        minute: minute // 0..59
    }        
}

.......
handleChange(e){
    this.setState({
       [e.target.id]: e.target.value
    });

    if(valid) this.props.handleChange(hourMinute);
}
.......

<input id="hour" type="number" inputMode="numeric" 
       step="1" pattern="[0-9]*" maxLength="2" autoComplete="off" 
       className="form-control"
       value={this.state.hour}
       onChange={this.handleChange}/>

<input id="minute" type="number" inputMode="numeric" 
       step="1" pattern="[0-9]*" maxLength="2" autoComplete="off" 
       className="form-control"
       value={this.state.minute}
       onChange={this.handleChange}/>

由于componentWillReceiveProps已贬值并且被认为是不安全的,并且对于getDerivedStateFromProps解释说,不应以将其复制到状态的方式来使用它,对于这种情况,正确的概念应该是什么?

2 个答案:

答案 0 :(得分:0)

您可以简单地将其作为prop发送到Child组件,并随其发送另一个function作为道具,Child将使用它来更新{{1} },例如,您所说的值有效时

Parent

然后根据您的逻辑在class Parent extends Component { constructor(props) { super(props); this.state = {minuteHour: 0}; this.handleValidNumber = this.handleValidNumber.bind(this); } handleValidNumber() { // ... } render() { return ( <div className="SuggestionBox"> <Child minuteHour={this.state.minuteHour} handleValidNumber={this.handleValidNumber} /> </div> ); } } 中调用Child,以防minHour值由其他组件在父级中更改,因为您说它将更新其状态并自动重新呈现,并且新的this.props.handleValidNumber()值将发送到props

Child

答案 1 :(得分:0)

尝试一下:

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {propToBeSentToChild:""};
    }

    handlechangedProp=(changedProp)=> {
        // ...
    }

    render() {
        return (
            <div className="SuggestionBox">
                <Child propForChild={this.state.propToBeSentToChild} handlechangedProp={this.handlechangedProp} />
            </div>
        );
    }
}

在子组件中,执行:

Class Child extends Component {
    constructor(props) {
        super(props);

    }

    handleButtonClick=()=> {
        let changedProp = this.props.propForChild;
        //do whatever you want to do with this changed prop and then pass
        //it back to the parent component's method
        this.props.handleChangedProp(changedProp) 
    }

    render() {
        <div>
            <button onClick={this.handleButtonClick}> Click button </button>
        </div>
    }
}