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 源码漂流(七)之 Fragment #56

Open
sisterAn opened this issue Sep 19, 2019 · 0 comments
Open

React 源码漂流(七)之 Fragment #56

sisterAn opened this issue Sep 19, 2019 · 0 comments

Comments

@sisterAn
Copy link
Owner

在 React 中,当我们需要渲染多个组件时:

const Hello = ({name})=>(
  <h1> Hello {name} </ h1> 
);
const Button = () => {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      {count}
    </button>
  );
};

当需要同时渲染以上两个组件时,它们不能直接渲染:

// 渲染失败
ReactDOM.render(<Button /><Hello />, document.getElementById('root'));  

解决方法一:元素数组的形式

ReactDOM.render([<Button />, <Hello />], document.getElementById('root'));

解决方法二:引入新的 DOM 父节点

ReactDOM.render(
  <div>
    <Button />
    <Hello />
  </div>,
  document.getElementById('root')
); // 需要引入新的 DOM 父节点

解决方法三:React.Fragment

ReactDOM.render(
  <React.Fragment>
    <Button />
    <Hello />
  </React.Fragment>,
  document.getElementById('root')
);

React.Fragment 简写

ReactDOM.render(
  <>
    <Button />
    <Display />
  </>,
  document.getElementById('root')
);
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