【问题标题】:How to build uncontrolled component with react hooks?如何使用反应钩子构建不受控制的组件?
【发布时间】:2020-02-10 09:05:18
【问题描述】:

如何将这个不受控制的组件翻译成react hooks(并避免输入字段的多重渲染):

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.input = React.createRef();
  }

  render() {
    const {onInputChanged} = this.props;
    return (
      <form>
        <input type="text" ref={this.input} onChange={onInputChanged}/>
      </form>
    );
  }
}

【问题讨论】:

  • 你为什么不看一些带有 Hooks 的功能组件的例子并尝试一下。然后,如果您遇到困难,请寻求帮助?这不是一个“我该怎么做”的问题,这是一个“为我做”的请求。
  • 我认为这是一个很好的例子,说明如何在 react hooks 中编写不受控制的组件。

标签: reactjs react-hooks


【解决方案1】:

【讨论】:

    【解决方案2】:
    import React, { useRef } from 'react';
    
    export const MyForm = (props) => {
      const input = useRef(null);
      return (
        <form>
          <input type="text" ref={input} onChange={props.onInputChanged} />
        </form>
      );
    }
    

    【讨论】:

    • 请不要只发布代码作为答案,而是说明您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
    【解决方案3】:

    如果您想将组件转换为功能组件并使用钩子,您可以这样做:

    import React, { useRef,useEffect } from 'react';
    
    useEffect(() => {
    
    },['the props you write here will trigger the re-render when they change'])
    const MyForm = (props) => {
      const input = useRef(null);
      return (
        <form>
          <input type="text" ref={input} onChange={props.onInputChanged} />
        </form>
      );
    }
    
    export default MyForm;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-27
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2020-08-30
      相关资源
      最近更新 更多