我是新來的反應,並試圖更新父母的狀態,但沒有運氣到目前爲止。如何更新父母的狀態?
組件
class InputBox extends Component {
constructor(props) {
super(props);
this.type = props.type;
}
render() {
return (
<div>
<input type={this.type}/>
</div>
);
}
}
其他容器,我想利用這個組件來切換密碼
constructor(props) {
super(props);
this.state = {
type: 'password',
wording: 'Show',
};
this.changeState = this.changeState.bind(this);
}
changeState() {
const oldState = this.state.type;
const isTextOrHide = (oldState === 'password');
const newState = (isTextOrHide) ? 'text' : 'password';
const newWord = (isTextOrHide) ? 'Hide' : 'Show';
this.setState({
type: newState,
label: newWord,
});
}
<Wrapper>
<InputBox type={this.state.type} />
<Toggle onClick={this.changeState}>{this.state.wording}</Toggle>
</Wrapper>
檢查這個答案https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs/38397755#38397755 –