我正在尝试在 ReactJS 中制作一个表单。 https://facebook.github.io/react/docs/forms.html例如,讲述如何创建 UI 元素,其中更改元素的值将触发 XYZ,其中发生事件的对象可以访问输入及其注释。
假设,在同一个较大的组件中,我有一个用于输入数据的 TEXTAREA,以及一个用于单击保存数据的按钮。
如何做正确的事情,以便单击按钮创建一个新的空白记录并将其“描述”字段初始化为 TEXTAREA 的内容?
谢谢
最佳答案
有很多方法可以做到这一点。一个简单的实现(忽略 Flux 和 kin)如下所示:
var React = require('react');
class Form extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {description: ''};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({[e.target.name]: e.target.value});
}
onSubmit(e) {
e.preventDefault();
fetch(this.props.formAction, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
description: this.state.description
})
});
this.setState({description: ''});
}
render() {
return (
<form action={this.props.action} method={this.props.method} onSubmit={this.onSubmit}>
<textarea onChange={this.onChange} name="description">
{this.state.description}
</textarea>
<button>Submit</button>
</form>
);
}
}
Form.propTypes = {
action: React.PropTypes.string.isRequired,
method: React.PropTypes.string,
}
Form.defaultProps = {
action: '/action/url',
method: 'post',
};
module.exports = Form;
使用 React 的组件方法 setState 来管理应用程序数据。当调用 onSubmit 时,防止浏览器默认行为与您的 ajax 版本相同。
如果使用 Flux,则该 fetch 调用将是一个 Action。
关于javascript - ReactJS 表单提交如何访问字段值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265171/