【发布时间】:2020-01-14 22:16:05
【问题描述】:
我是新手,所以请多多包涵。
我想做什么:
本质上是将数据从子组件传递到父组件,然后再传回另一个子组件。
<ParentComponent>
<ChildComponent1>
<ChildComponent2>
</ParentComponent>
子 Component1 有一个表单。
提交表单时...
1.) 应使用表单的内容更新状态。
2.) 状态数据应该传递到父组件。
3.) 父组件应将数据传递到 ChildComponent2
4.) ChildComponent2 现在可以访问 ChildComponent1 的数据,并且可以操作所述数据。
#4 是我的目标,但我似乎坚持 #2。我认为我在逻辑上做的一切都是正确的,但我不确定。当我在提交表单后检查我的父状态时,该状态看起来仍处于其初始状态 ('')。
这是我的代码。
import styles from './Body.module.css';
import {LeftPortion} from './LeftPortion/LeftPortion.js';
import RightPortion from './RightPortion/RightPortion.js';
class Body extends Component {
constructor(props){
super(props)
this.state={
teamOne: '',
teamTwo: ''
};
this.updateBetInfo = this.updateBetInfo.bind(this);
}
updateBetInfo(firstTeam, secondTeam){
this.setState({teamOne: firstTeam, teamTwo: secondTeam})
}
render(){
return(
<div className={styles.container}>
<LeftPortion updateParent={this.updateBetInfo}/>
<RightPortion/>
</div>
);
}
}
export default Body;
import styles from './LeftPortion.module.css';
export class LeftPortion extends Component{
constructor(props){
super(props)
this.state={
teamOne:'',
teamTwo:''
}
this.onChange= this.onChange.bind(this);
this.onSubmitForm= this.onSubmitForm.bind(this);
}
onChange(event){
this.setState({[event.target.name]: event.target.value})
}
onSubmitForm(teamOne, teamTwo){
var teamOne = this.state.teamOne;
var teamTwo = this.state.teamTwo;
this.props.updateParent(teamOne,teamTwo)
}
render(){
return(
<div className={styles.container}>
<h4>Enter bet info here:</h4>
<h4>-------------------</h4>
<h4>Straight bet</h4>
<div className={styles.teamEntry}>
<form>
<label>
Team 1:
<input type="text" name="teamOne"onChange={this.onChange}/>
</label>
<br/>
<label>
Team 2:
<input type="text" name="teamTwo" onChange={this.onChange}/>
</label>
<br/>
<input type="submit" value="Submit" onClick={this.onSubmitForm}/>
</form>
<br/>
<div className={styles.betType}>
<form>
<label>
Bet:
<select>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='X'>X</option>
</select>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
</div>
</div>
);
}
}
基本上我坚持的是,当提交表单时,我需要将状态更新到从子组件进入表单的 teamOne 和 teamTwo。
【问题讨论】:
标签: reactjs react-props data-management react-state-management