hushicai / hushicai.github.io

Blog
https://hushicai.github.io
27 stars 1 forks source link

React Ref #63

Open hushicai opened 5 years ago

hushicai commented 5 years ago

React Ref的发展历程:

facebook/react#1373

hushicai commented 5 years ago

React ref 的前世今生

hushicai commented 5 years ago

string ref

string ref无法绑定到当前的"所有者":

class Child extends React.Component {
  componentDidMount() {
   // `test` ref is here
    console.log("child", this.refs);
  }
  render() {
    let { renderer } = this.props;

    return renderer && renderer();
  }
}

class Parent extends React.Component {
  componentDidMount() {
   // empty object
    console.log("parent", this.refs);
  }
  render() {
    return (
      <Child
        renderer={() => {
          // ref属于调用者`Child`,而不是当前的`Parent`
          return <input ref="test" placeholder="ref test" />;
        }}
      />
    );
  }
}