Javascript 试图将用户输入的li从ul输入到数组中
我有一个将内容添加到ul的输入,我试图将li放入一个数组中,以便在其他地方使用Javascript 试图将用户输入的li从ul输入到数组中,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个将内容添加到ul的输入,我试图将li放入一个数组中,以便在其他地方使用 <input className="input-fields" maxLength="25" id="ingredient" type="text" placeholder="Ingredient"
<input
className="input-fields"
maxLength="25"
id="ingredient"
type="text"
placeholder="Ingredient"
onKeyPress={this.handleKeyPress}
/>
<ul
ref={input => (this.ingredients = input)}
id="recipeItems"
className="recipe-items"
/>
您应该从组件的状态获取
ul
中的数据,而不是直接从ul
DOM获取数据。在输入
中键入成分
时,应更改组件的状态,然后组件将根据新状态重新渲染(包括ul
元素)。一旦您需要成分
,只需从组件的状态获取它们即可。使用React时,请记住根据组件的状态执行操作。一种方法是将li数据存储在状态中。这允许您使用当前组件的任何子组件中的数据。但是,如果希望在该数据之外使用数据(例如当前数据的父组件),则可能需要状态管理库,如或
下面是一个如何在组件状态下存储li数据的示例
类容器扩展React.Component{
构造函数(){
超级();
此.state={
配料:[]//您可以使用以下命令将此数据传递给此处的任何子组件
};
}
HandleaddingCredit=(e)=>{
e、 预防默认值();
const newcomponent=e.target.children[0]。值;
this.setState((prevState)=>({
成分:prevState.Components.concat([新成分])
}))
}
render(){
返回
}
}
类IngreditList扩展了React.Component{
render(){
返回
配料表
{this.props.data.map((ing,i)=>- {ing}
)}
}
}
ReactDOM.render(,document.getElementById('app'))
谢谢您,在您的环境中思考这一点确实帮助了我,欢迎您。您可以将此答案标记为已接受,以便对遇到类似问题的人更为明显。
createRecipe(e) {
e.preventDefault();
const recipe = {
name: this.name.value,
ingredients: this.ingredients.value,
instructions: this.instructions.value
};
console.log(recipe);
}