使用React.createRef创建引用而不在React中使用构造函数?

dea*_*904 8 javascript ref reactjs

基本上,我只用constructorReact3个原因-

1.如要初始化state-

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { counter: 0 };
    }
}
Run Code Online (Sandbox Code Playgroud)

但是由于Babel的班级领域支持,我不再使用它

class App extends React.Component {
    state = { counter: 0 };
}
Run Code Online (Sandbox Code Playgroud)

2. bind像-

class App extends React.Component {
    constructor(props) {
        super(props);
        this.increment.bind(this);
    }

    increment() {

    }
}
Run Code Online (Sandbox Code Playgroud)

但是由于arrow功能原因,我不再这样做了

class App extends React.Component {
    increment = () => {

    }
}
Run Code Online (Sandbox Code Playgroud)

3.如要使用createRef-

class App extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }
}
Run Code Online (Sandbox Code Playgroud)

那我可以React.createRef不用constructor在React中使用吗?

Ana*_*dac 13

您可以像一样将其声明为类字段state

class App extends React.Component {
  state = { counter: 0 };
  inputRef = React.createRef();
}
Run Code Online (Sandbox Code Playgroud)

Babel会将其转换为第二阶段预设中的以下代码。

constructor(props) {
    super(props);

    this.state = { counter: 0 };
    this.inputRef = React.createRef();
  }
Run Code Online (Sandbox Code Playgroud)


Chr*_*ris 7

是的你可以。例如:

const MyComponent = () => {
  const inputRef = React.createRef();

  return (
    <input ref={inputRef} />
  );
}
Run Code Online (Sandbox Code Playgroud)

您唯一不能做的就是将ref属性传递给功能组件:

render() {
  // This won't work.
  return <MyFunctionalComponent ref={this.inputRef} />
}
Run Code Online (Sandbox Code Playgroud)

来自官方文档的更多信息,在这里

但是,ref只要您引用 DOM 元素或类组件,就可以在函数组件中使用该属性: