Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

推荐 React V16.3 新增的三个非常实用的 API #255

Open
GuoYongfeng opened this issue Mar 30, 2018 · 0 comments
Open

推荐 React V16.3 新增的三个非常实用的 API #255

GuoYongfeng opened this issue Mar 30, 2018 · 0 comments

Comments

@GuoYongfeng
Copy link
Member

React.createContext()

应用的状态管理,大家很容易想到 redux 和 mobx。但什么样的项目需要,也是一个争议的话题。对于应用的逻辑没那么复杂的情况,不建议用,甚至社区还给了 react-broadcast 这个方法,通过事件机制的方式来解决数据的传递和响应。这次给的 createContext 方法就是来把这个实践官方化。

// Theme context, default to light theme
const ThemeContext = React.createContext('light');

// Signed-in user context
const UserContext = React.createContext();

// An intermediate component that depends on both contexts
function Toolbar(props) {
  return (
    <ThemeContext.Consumer>
      {theme => (
        <UserContext.Consumer>
          {user => (
            <ProfilePage user={user} theme={theme} />
          )}
        </UserContext.Consumer>
      )}
    </ThemeContext.Consumer>
  );
}

class App extends React.Component {
  render() {
    const {signedInUser, theme} = this.props;

    // App component that provides initial context values
    return (
      <ThemeContext.Provider value={theme}>
        <UserContext.Provider value={signedInUser}>
          <Toolbar />
        </UserContext.Provider>
      </ThemeContext.Provider>
    );
  }
}

React.createRef()

关于如何获取 DOM 节点,以及各自姿势的比较,之前方案比较多,这次给的方案比较折中,写法能接受,而且没有啥副作用。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

React.Fragment()

最早的时候,render 方法只能返回一个节点,多了会报错;后来变成了可以 return 出来一个数组。而这次,React.Fragment 组件可以让我们在 render() 方法中返回多个元素节点,挺直观的。

render() {
  return (
    <React.Fragment>
      Some text.
      <h2>A heading</h2>
    </React.Fragment>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant