问题描述
我无法在Form中将值设置为Inputfield.下面是我的代码.即使我也尝试提供直接值,就像输入元素中的value='ABC'
一样.但没有运气.当我尝试在
i cannot able to set value to the Inputfield in Form. below is my code. even i tried to give direct value too like in value='ABC'
in input element. but no luck. when i tried to display value outside Form Tag like
<h1>{this.state.company.companyCode}</h1>
这显示了价值.但不在Form内.
this shows value. but not inside Form.
class UpdateCompany extends Component {
constructor(props) {
super(props);
this.state = {
companycode: { value: ''},
company: ''
};
this.loadCompanydetail = this.loadCompanydetail.bind(this);
}
loadCompanydetail(companyid) {
GetCompanyById(companyid)
.then(response => {
this.setState({
company: response
});
}).catch(error => {
if(error.status === 404) {
this.setState({
notFound: true,
isLoading: false
});
} else {
this.setState({
serverError: true,
isLoading: false
});
}
});
}
componentDidMount(){
const companyid =this.props.match.params.companyId;
this.loadCompanydetail(companyid);
}
render() {
const { getFieldDecorator } = this.props.form
return (
<h1 className="page-title">Edit Company - {this.state.company.companyCode}</h1>
<Form>
<Form.Item label="Company Code">
{getFieldDecorator('companycode', {
rules: [
{
required: true,
message: 'Please enter Code',
max: 3,
},
],
})(<Input name="companycode" value={this.state.company.companyCode} />)}
</Form.Item>
<Form.Item wrapperCol={{ span: 12, offset: 6 }}>
<Button type="primary"
htmlType="submit"
size="large">Submit</Button>
</Form.Item>
</Form>
);
}
}
推荐答案
您的问题似乎有点偶然.据我了解,您正在尝试在用户输入时设置输入字段的值.您需要在输入字段中使用 onChange 事件处理程序.另外,我建议您不要在状态内使用嵌套对象.这是一种简单的方法
Your question seems a little hit and miss. From my understanding, you are trying to set the value of the input field as the user types in. You need to use the onChange event handler with the input field. Also, I would suggest you to not use nested objects inside the state. Here's a simple approach
state = {
companyCode: ''
};
现在,在用于输入字段的渲染函数中,您需要使用onChange处理程序:
Now, Inside your render function for the input field you need to use a onChange handler:
<input type="text" name="companyCode" value={this.state.companyCode} onChange={this.handleChange} />
您可以在render函数之外定义handleChange函数.另外,您可以使用箭头功能来避免对此进行绑定.这是一个示例:
You can define the handleChange function outside the render function. Also, you can use arrow functions to avoid binding to this. Here's an example:
handleChange = e => {
this.setState({ companyCode: e.target.value });
}
了解有关事件的更多信息.
这篇关于如何在formField ReactJs中设置输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!