【发布时间】:2016-04-03 10:55:48
【问题描述】:
我已经用 ReactJS 和 ES6 进行了几天的试验,并创建了几个组件,即 <InputText />、<InputNumber />、<InputEmail />,它们正在组件 <ContactsEdit /> 中使用。
尽管我已经阅读了很多教程,但我的子组件拒绝 render() 和 {this.state.Firstname} 似乎真的很奇怪,即使我尝试了 componentWillMount、componentDidMount、this.setState、this.state 和 this.forceUpdate() ,但他们会很好地呈现this.props.Firstname
我欢迎任何形式的建议或帮助。可以在github找到源代码
谢谢:)
` 导出默认类 ContactsEdit 扩展 React.Component {
constructor(props) {
super(props);
this.contactId = this.props.params.id;
this.persistence = new Persistence('mock');
this.state = {
contact : {}
};
}
componentDidMount() {
this.persistence.getContactById( this.contactId ).then( (resolve) => {
this.setState({ contact : resolve.data });
this.data = resolve.data;
}).catch( (reject) => {
console.log(reject);
}) ;
this.forceUpdate();
}
onChange(id,newValue) {
this.state.contact[ id ] = newValue;
this.forceUpdate();
}
saveRecord( object ) {
console.log( this.state );
}
render() {
return (
<div className="ContactsEdit">
<h2>Contact Edit (Parent) id : {this.props.params.id}, FullName : {this.state.contact.Firstname} {this.state.contact.Lastname}</h2>
<div className="row">
<InputText id="Firstname" fieldName={this.state.contact.Firstname} labelName="Firstname" onChange={this.onChange.bind(this)} divClass="col-lg-3 col-md-3 col-sm-3 col-xs-6" />
<InputText id="Lastname" fieldName={this.state.contact.Lastname} labelName="Lastname" onChange={this.onChange.bind(this)} divClass="col-lg-3 col-md-3 col-sm-3 col-xs-6" />
<InputText id="SocSecId" fieldName={this.state.contact.SocSecId} labelName="SocSecId" onChange={this.onChange.bind(this)} divClass="col-lg-3 col-md-3 col-sm-3 col-xs-6" />
<InputText id="DriverLicId" fieldName={this.state.contact.DriverLicId} labelName="DriverLicId" onChange={this.onChange.bind(this)} divClass="col-lg-3 col-md-3 col-sm-3 col-xs-6" />
</div>
</div>
)
}
}
`
` 导出默认类 InputText 扩展 React.Component {
constructor(props) {
super(props);
this.state = { fieldName : this.props.fieldname};
}
componentWillMount() {
//this.state.fieldName = this.props.fieldname;
//this.forceUpdate();
}
updateState(evt) {
//this.setState( {fieldName : evt.target.value} );
this.props.onChange( evt.target.id, evt.target.value );
}
render() {
return (
<div className={this.props.divClass}>
<hr />
<label> {this.props.labelName} </label>
<div>{this.props.fieldName}</div>
<div>{this.state.fieldName}</div>
<input
type="text"
id={this.props.id}
value={this.props.fieldName}
onChange={this.updateState.bind(this)}
className="form-control"
/>
</div>
)
}
} `
【问题讨论】:
-
欢迎来到堆栈!只需在您的问题中发布相关代码,这将(希望)消除反对意见并为您提供所需的答案。
-
谢谢 :) 我会这样做的 :)
标签: javascript reactjs react-jsx