/** * 子組件如何更改父組件的state呢? * 父組件傳遞下來的props不滿足要求,往往需要修改 * * * Author: shujun * Date: 2020-10-25 */ import React from 'react'; export default class Father extends React.Component{ state = { inputValue: 'shujun', objValue: {'name': 'jay', 'sex': 'boy'} }; changeInputValue = (e)=> { this.setState({inputValue: e.target.value}); } changeObjValue = (e)=> { let objValue = this.state.objValue; objValue.name = e.target.value; this.setState({objValue}); } render(){ const {inputValue, objValue} = this.state; return <div style={{width: '600px', paddingBottom: '20px', border: '1px solid red' }}> <h3>father:</h3> <p> react的state是可以修改,props是不讓修改的,為什么要這么做呢,還不理解 ,,ԾㅂԾ,, <br/> 但是我現在就是想要修改props, 因為這樣的場景很多:父組件傳遞下來的props不滿足要求,往往需要修改 </p> <input value={inputValue} onChange={this.changeInputValue}/> state: inputValue -- {inputValue} <br/> <input value={objValue.name} onChange={this.changeObjValue}/> state: objValue -- {JSON.stringify(objValue)} <br/> <Son1 inputValue={inputValue} objValue={objValue} /> <Son2 inputValue={inputValue} objValue={objValue} changeInputValue={this.changeInputValue} changeObjValue={this.changeObjValue} /> </div> } } class Son1 extends React.Component { constructor(props){ super(); this.state = {flag: true}; } changeInputProps = (e)=> { this.props.inputValue = e.target.value; } changeObjProps = (e)=> { console.log(e.target.value); let objValue = this.props.objValue; objValue.name = e.target.value; console.log(objValue); this.setState({flag: true}); } render() { const {inputValue, objValue} = this.props; return <div style={{border: '1px solid green', marginTop: '20px'}}> <h3>Son1: </h3> <p> 只要props是對象,不改對象指針,只修改對象里面的內容, 照樣能修改props, O(∩_∩)O <br/> 但是注意:在change props后,一定要假裝在setState, 引發render </p> <input value={inputValue} onChange={this.changeInputProps}/> props: inputValue -- {inputValue} <br/> <input value={objValue.name} onChange={this.changeObjProps}/> props: objValue -- {JSON.stringify(objValue)} <br/> </div>; } } class Son2 extends React.Component { changeObjProps = (e)=> { this.props.changeObjValue(e); } render() { const {inputValue, objValue} = this.props; return <div style={{border: '1px solid green', marginTop: '20px'}}> <h3>Son2: </h3> <p> 1. 父組件傳遞修改方法下來,子組件中調用父組件方法,修改的實際是父組件的state <br/> 2. 父組件state修改了, </p> <input value={inputValue} onChange={(e)=>this.props.changeInputValue(e)}/> props: inputValue -- {inputValue} <br/> <input value={objValue.name} onChange={this.changeObjProps}/> props: objValue -- {JSON.stringify(objValue)} <br/> </div>; } }
運行效果: