React isValidElement comes out as false

前端 未结 3 1914
我寻月下人不归
我寻月下人不归 2021-02-15 22:28

Here is a simple example:

const Foo = () => {
    return (
    
foo
); } class Bar extends React.Component { render() { retur
相关标签:
3条回答
  • 2021-02-15 22:54

    Component != Element

    Foo and Bar are components. An element is basically the result of "instantiating" (also not really, not sure what the right term is) a component. It's the combination of a constructor/function/string (for HTML components), props and children.

    You get an element when you call React.createElement(Foo), which is what <Foo /> is doing under the hood.

    const Foo = () => {
        return (
        <div>foo</div>
      );
    }
    console.log(React.isValidElement(<Foo />));
    console.log(<Foo bar={42} />);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

    0 讨论(0)
  • 2021-02-15 23:16

    To check for a function component:

    typeof Foo === 'function'
    
    0 讨论(0)
  • 2021-02-15 23:19
    const Foo = () => <div>foo</div>;
    
    class Bar extends React.Component {
        render() {
           return (
              <div>bar</div>
           )
        }
    }
    
    console.log(React.isValidElement(<Foo />));
    console.log(React.isValidElement(<Bar />));
    
    0 讨论(0)
提交回复
热议问题