我正在尝试从一个请求API的child Component
中以多个parent Component
保存多个表单。
我尝试使用Context
和reducer
。
它奏效了,但我想知道方法是否最佳?
我的项目是这样的:
import React from 'react'
const MasterForm = () => {
const saveAll = () => {
CallAPI();
}
return(
<>
<button onClick={saveAll} />
<FormOfTable1/>
<FormOfTable2/>
</>
)
}
对我有什么解决方案或建议吗? 谢谢!
答案 0 :(得分:0)
从状态中获取值,并从输入中构建数据。例如。
state = {
name: '',
address: '',
}
在表单中为输入添加事件处理程序
<form>
<label>
Name:
<input value={this.state.name} onChange={this.handleChange} type="text" name="name" />
</label>
</form>
<form>
<label>
Address:
<input value={this.state.address} onChange={this.handleChange} type="text" name="address" />
</label>
</form>
<button onClick={this.saveAll}>Submit</button>
发送数据
saveAll = () => {
// build data from both forms
const { name, address } = this.state;
axios.post(`https://jsonplaceholder.typicode.com/users`, {
name,
address
})
.then(res => {
console.log(res);
console.log(res.data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component {
state = {
name: '',
address: '',
}
saveAll = (e) => {
e.preventDefault();
// build data from both forms
const { name, address } = this.state;
console.log('name: ',name, '|| address: ', address);
// axios.post(`https://jsonplaceholder.typicode.com/users`, {
// name,
// address
// })
// .then(res => {
// console.log(res);
// console.log(res.data);
// });
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return (
<div>
<h3>form 1</h3>
<form>
<label>
Name:
<input value={this.state.name} onChange={this.handleChange} type="text" name="name" />
</label>
</form>
<h3>form 2</h3>
<form>
<label>
Address:
<input value={this.state.address} onChange={this.handleChange} type="text" name="address" />
</label>
</form>
<button onClick={this.saveAll}>Submit</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
答案 1 :(得分:0)