react 纯函数组件中使用ref属性方法

1.您不能ref在功能组件上使用该属性,因为它们没有实例: 如下

function MyFunctionalComponent() {
  return ;
}

class Parent extends React.Component {
  render() {
    // This will *not* work!
    return (
       { this.textInput = input; }} />
    );
  }
}

2.class定义的组件 或者函数组件返回dom元素 这两种方式是可以运用ref属性的 如下:

function CustomTextInput(props) {
  // textInput must be declared here so the ref callback can refer to it
  let textInput = null;

  function handleClick() {
    textInput.focus();
  }

  return (
    
type="text" ref={(input) => { textInput = input; }} /> type="button" value="Focus the text input" onClick={handleClick} />
); }

你可能感兴趣的:(工作中的零碎知识)