Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 试图将用户输入的li从ul输入到数组中_Javascript_Reactjs_Ecmascript 6 - Fatal编程技术网

Javascript 试图将用户输入的li从ul输入到数组中

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"

我有一个将内容添加到ul的输入,我试图将li放入一个数组中,以便在其他地方使用

                <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);
  }