开发!有谁可以帮助我吗?
我正在尝试从Meteor中的React设置state
并从输入中编辑此state
数据,它看起来像
class Profile extends Component{
constructor(props){
super(props);
this.editProfileBind = this.editProfile.bind(this);
this.testEmailBind = this.testEmail.bind(this); }
testEmail(e){
const input = e.target;
this.setState({
email: input.value
});
input.value = this.state.email;
}
editProfile(e){
e.preventDefault();
}
render(){
return(
<form className="col-md-4 col-xs-6"
onSubmit={this.editProfileBind}>
<input type="email"
onChange={this.testEmailBind}
value={this.props.email || ''}
/>
<button type="submit">Submit</button>
</form>
)
}
} // end component
export default createContainer(() => {
const user = Meteor.user();
const email = user.emails && user.emails[0].address;
return { email };
}, Profile);
您能否建议我如何设置this.state.email
来代替this.props.email
?谢谢!
答案 0 :(得分:4)
对代码产生问题:
<强> 1。使用道具初始化州
在构造函数中,您需要将初始状态设置为传入的email
道具。
<强> 2。输入value
应该等于this.state.email
该值未更新,因为您要将值设置为传入的prop(不会更改),而不是email
函数正在更新的testEmail
状态。
第3。使用新道具更新州
您需要添加componentWillReceiveProps
函数,以便在将新数据传递到email
组件时更新Profile
状态。
Profile
组件应如下所示:
class Profile extends Component{
constructor(props){
super(props);
this.editProfileBind = this.editProfile.bind(this);
this.testEmailBind = this.testEmail.bind(this);
this.state = {
email: props.email
}
}
testEmail(e){
const input = e.target;
this.setState({
email: input.value
});
}
editProfile(e){
e.preventDefault();
}
componentWillReceiveProps(nextProps){
this.setState({
email: nextProps.email
});
}
render(){
return(
<form className="col-md-4 col-xs-6"
onSubmit={this.editProfileBind}>
<input type="email"
onChange={this.testEmailBind}
value={this.state.email}
/>
<button type="submit">Submit</button>
</form>
)
}
} // end component
export default createContainer(() => {
const user = Meteor.user();
const email = user.emails && user.emails[0].address;
return { email };
}, Profile);