类型错误:无法读取 Reactjs

时间:2021-02-07 01:43:06

标签: javascript reactjs web react-router undefined

我对 React 不是很精通。我正在使用动态表单,用户应该能够在其中动态添加和删除输入字段。但是,我无法将输入动态保存到变量中。

代码:


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      values: [],
      type:[],
      name: '',
      frequency: '',
    };
  } 

  handleMetric(i, event) {
     let values = [...this.state.values];
     values[i] = event.target.value;
     this.setState({ values });
     console.log("Metrics: ")
     console.log(values) 
  }

  handleThreshold(i, event) {
    let values = [...this.state.values];
    values[i] = event.target.value;
    this.setState({ values });
    console.log("Threshold: ")
     console.log(values) 
  }

  addClick(){
    this.setState(prevState => ({ values: [...prevState.values, '']}))
  }
  
  removeClick(i){
     let values = [...this.state.values];
     values.splice(i,1);
     this.setState({ values });
  }

  createUI(){
    return this.state.values.map((el, i) => 
        <div key={i}>
         <input type="text" value={el||''} onChange={this.handleChange.bind(this, i)} />
         <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/>
        </div>          
    )
 }
  
  render() {

    return (
    <div> 
       <div className="card">
          <form onSubmit={this.handleSubmit}>
         
              <Form.Item name="Type of metrics" label="Metric" htmlFor="type">
                <Select
                  value={Select}
                  onChange={this.handleMetric}
                  options={metrics}
                />
              </Form.Item>

              <Form.Item name="amount" label="Threshold Score" htmlFor="threshold">
                <Slider marks={marks} name="threshold" onChange={this.handleThreshold} />
              </Form.Item>

            </Form>

            {this.createUI()}  

            <input type='button' value='add more' onClick={this.addClick.bind(this)}/>
            <input type="submit" value="Submit" />

          </form>
        </div>
      </div>
    );
  }
}

export default App

handleThreshold 和 handleMetric 函数都不起作用,并给出以下错误: enter image description here

enter image description here

非常感谢您在动态获取数组中存储的变量方面的帮助。

1 个答案:

答案 0 :(得分:1)

将类方法转换为带有箭头函数的类属性初始值设定项,因此 this 始终是组件实例:

  handleMetric = (i, event) => {
     let values = [...this.state.values];
     values[i] = event.target.value;
     this.setState({ values });
     console.log("Metrics: ")
     console.log(values) 
  };

  handleThreshold = (i, event) => {
    let values = [...this.state.values];
    values[i] = event.target.value;
    this.setState({ values });
    console.log("Threshold: ")
     console.log(values) 
  };

您通过在 this.addClick.bind(this) 方法中执行 render 为另一个回调解决了这个问题。这两种方法都有效。执行箭头函数声明意味着在组件的生命周期中只创建 1 个函数,而 .bind 中的 render 表示每次调用 render 都会创建 1 个函数。这可能不会对您的应用产生可识别的性能变化,但需要考虑。