【问题标题】:Arrow function into "ordinary" function expression in react component箭头函数在反应组件中变成“普通”函数表达式
【发布时间】:2020-01-25 17:29:38
【问题描述】:

我想把这个react组件中的箭头样式函数(at onChange)改成普通函数。我是初学者,对我来说,并排查看两个版本很有帮助,因为我很难掌握新的箭头函数语法。

这应该是可能的,但是使用“普通”函数会如何?

import React from "react";

function Input1(props) {
  //console.log(props)
  return (
    <div>
      <input
        onChange={event => props.handleChange("email", event.target.value)}
      />
    </div>
  );
}

export default Input1;

【问题讨论】:

  • function (event) { return props.handleChange("email", event.target.value); } ?
  • 如果你只是想要一个多行函数,只需要使用event =&gt; { /* multi-line of code here */ } 就可以了。

标签: javascript reactjs arrow-functions react-component


【解决方案1】:
 <div>
  <input
    onChange={function(event) {
          props.handleChange("email", event.target.value)
         }
   }
  />
</div>

【讨论】:

    【解决方案2】:
    import React from "react";
    
    function Input1(props) {
      //console.log(props)
    
      function onChange(event) {
        props.handleChange("email", event.target.value)
      }
    
      return (
        <div>
          <input
            onChange={onChange}
          />
        </div>
      );
    }
    
    export default Input1;
    

    【讨论】:

      【解决方案3】:
      import React from "react";
      
      function Input1(props) {
      
        function changeHandler(event) {
           props.handleChange("email", event.target.value)
        }
      
        //console.log(props)
        return (
          <div>
            <input
              onChange={changeHandler}
            />
          </div>
        );
      }
      
      export default Input1;
      

      【讨论】:

        【解决方案4】:
        import React from "react";
        
        class Input1 extends React.Component {
         constructor(props) {
            super(props);
            //need to bind in case of using function decleration
            this.handleChange = this.handleChange.bind(this);
          }
        
         handleChange(event){
           props.handleChange("email", event.target.value);
          }
        
         render() {
           return (
            <div>
              <input
                onChange={this.handleChange}
              />
            </div>
           )
         }
        

        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-04-12
          • 2017-03-13
          • 2020-05-07
          • 2019-02-24
          • 2019-01-17
          • 2017-01-06
          • 2015-11-03
          • 2015-11-05
          相关资源
          最近更新 更多