Reactjs 如何获取文本字段值并将该值推送到arrayList

Reactjs 如何获取文本字段值并将该值推送到arrayList,reactjs,react-redux,Reactjs,React Redux,如何获取文本字段值并将该值推送到react js中的arrayList 我想从文本框中获取值,并将其推送到Modules数组中,以便通过迭代来呈现这些值 我试图使用ref,但出现了错误 你能帮我吗 constructor(props) { super(props); this.state={ module:'', Modules: [] } } ch

如何获取文本字段值并将该值推送到react js中的arrayList

我想从文本框中获取值,并将其推送到Modules数组中,以便通过迭代来呈现这些值

我试图使用ref,但出现了错误

你能帮我吗

 constructor(props) {
            super(props);
          this.state={
            module:'',
            Modules: []
          }
        }

        change (event){
            this.setState({
              [event.target.name]:event.target.value
            });
          };

        createModule (e) {
          e.preventDefault();
          console.log("submitted",this.state.module);
          this.setState(previousState => ({
              ...state,
              thisModules: [...previousState.Modules, 'new value']
          }));
        };

      render(){
        return(

            <form className="form-inline">
                  <div className="form-group">
                            Module Name:
                            <input type="text" id="module" 
                                name="module" 
                                  placeholder="module"  
                                    className="form-control" 
                                      ref="Module"
                                        value ={this.state.module}
                                          onChange={event => this.change(event)}/>
                  <button type="submit" className="btn btn-primary" onClick={(event) => this.createModule(event)}>Add Module</button>
                    </div>
            </form>
构造函数(道具){
超级(道具);
这个州={
模块:“”,
模块:[]
}
}
变化(事件){
这是我的国家({
[event.target.name]:event.target.value
});
};
创建模块(e){
e、 预防默认值();
console.log(“已提交”,this.state.module);
this.setState(previousState=>({
……国家,
thisModules:[…previousState.Modules,“新值”]
}));
};
render(){
返回(
模块名称:
this.change(event)}/>
this.createModule(event)}>Add模块
mylist.push(document.getElementById('textbox\u id').value)

以mylist作为列表,以textbox\u id作为文本框的id应该可以工作


考虑到这是纯javascript,因为我看不出react与react有什么区别。

运行代码的主要问题是,在
createModule
中,您没有将
放在
状态
前面。如果您给出了错误的详细信息,这会有所帮助

还有一些其他的打字错误,下面是一个工作解决方案

class ModuleList扩展了React.Component{
建造师(道具){
超级(道具);
这个州={
模块:“”,
模块:[]
}
}
变化(事件){
这是我的国家({
[event.target.name]:event.target.value
});
}
创建模块(e){
e、 预防默认值();
console.log(“已提交”,this.state.module);
this.setState(previousState=>({
…这个州,
模块:[…previousState.Modules,this.state.module]
}));
};
render(){
返回(
模块名称:
this.change(event)}/>
this.createModule(event)}>Add模块
    { 此.state.Modules.map( (m) =>
  • {m}
  • ) }
); } } ReactDOM.render( , document.getElementById('root')) );

我的应用程序:


到目前为止,您的代码是什么样子的?请发布它好吗?我想获取文本字段值并将该值推送到ArrayList,这样我就可以呈现这些值。谢谢Piran,非常感谢。我犯了一些错误。谢谢您的指导。还有一件事,我如何将模块数组从这个组件传递到其他组件,以及我如何能够访问该组件中的数组。@mohan这确实是一个非常不同的问题,应该在单独的SO问题中提出。这取决于您是想将模块传递给内部组件、父组件还是任何其他组件。如果答案是后者,那么您应该开始考虑使用redux或类似的库。