反应:将状态值作为参数传递给方法

时间:2019-03-06 18:49:26

标签: javascript reactjs forms

我想让我的班级更具可重用性。我要处理的表单很大,我不想为每个输入编写单个方法。如何将状态值作为参数传递给方法?

我正在尝试:

  state = {
    subtitle: ""
  };


  inputHandler = (e, param) => this.setState({ [param]: e.target.value });

  render() {
    return (
      <>
        {this.state.title}
        <input
          type="text"
          value={this.state.subtitle}
          onChange={e => this.inputHandler(this.state.subtitle)}
        />
      </>
    );
  } 

以及此解决方案的不同相似组合。

演示:https://codesandbox.io/s/kw6pnxwv0v

1 个答案:

答案 0 :(得分:2)

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  state = {
    subtitle: ""
  };

  onChange = (e) => {
    const target = e.target;
    const value = target.value;
    const name = target.name;

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

  render() {
    return (
      <>
        {this.state.title}
        <input
          type="text"
          name="subtitle"
          value={this.state.subtitle}
          onChange={this.onChange}
        />
        {this.state.subtitle}
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

让我知道这是否有帮助:)