我是React的新手,想要开发简单的应用程序-我想从中获取值和呈现列表的输入字段。在文本字段中添加选项后,我想使用新选项更新此列表。 setState函数不起作用,我不知道如何连接输入提交和列表呈现。我的代码在下面。
WaterApp.js
import React from 'react';
import AddWater from './AddWater';
import WaterElements from './WaterElements';
export default class WaterApp extends React.Component {
state = {
quantities: ['aaaaa', 'bbbbb', 'ccccc']
};
handleAddQuantity = (quantity) => {
this.setState(() => ({
quantities: ['ddddd', 'eeeee']
}));
console.log('works');
}
render() {
return (
<div>
<WaterElements quantities={this.state.quantities} />
<AddWater handleAddQuantity={this.handleAddQuantity} />
</div>
)
}
}
AddWater.js
import React from 'react';
export default class AddWater extends React.Component {
handleAddQuantity = (e) => {
e.preventDefault();
const quantity = e.target.elements.quantity.value;
console.log(quantity);
};
render() {
return (
<form onSubmit={this.handleAddQuantity}>
<input type="text" name="quantity" />
<input type="submit" value="Submit" />
</form>
)
}
}
WaterElements.js
import React from 'react';
const WaterElements = (props) => (
<div>
<p>Water Quantity:</p>
{
props.quantities.map((quantity) =>
<p key={quantity}>{quantity}</p>
)
}
</div>
);
export default WaterElements;
我希望此刻列表为ddddd,eeeee。
答案 0 :(得分:2)
您永远不会打电话给let data = window.parent.onFinished();
console.log(data);
props.handleAddQuantity
答案 1 :(得分:0)
this.setState(() => ({
quantities: ['ddddd', 'eeeee']
}));
应该是
this.setState({
quantities: ['ddddd', 'eeeee']
});
然后添加
this.setState({
quantities: [...state.quantities, quantity]
});
答案 2 :(得分:0)
使用此格式更新
this.state({key:value});
not this.state(()=>{key:value});
handleAddQuantity = (quantity) => {
this.setState({
quantities: ['ddddd', 'eeeee']
}));
console.log('works');
}