admin管理员组文章数量:1205733
Here is a simple example:
const Foo = () => {
return (
<div>foo</div>
);
}
class Bar extends React.Component {
render() {
return (
<div>bar</div>
)
}
}
console.log(React.isValidElement(Foo));
console.log(React.isValidElement(Bar));
Both of these return false. Why is that?
Here is a simple example:
const Foo = () => {
return (
<div>foo</div>
);
}
class Bar extends React.Component {
render() {
return (
<div>bar</div>
)
}
}
console.log(React.isValidElement(Foo));
console.log(React.isValidElement(Bar));
Both of these return false. Why is that?
Share Improve this question asked Sep 26, 2017 at 17:55 KoushaKousha 36.2k59 gold badges186 silver badges313 bronze badges 4 |3 Answers
Reset to default 17Component != 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>
To check for a function component:
typeof Foo === 'function'
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 />));
本文标签: javascriptReact isValidElement comes out as falseStack Overflow
版权声明:本文标题:javascript - React isValidElement comes out as false - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738691827a2107141.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
console.log(React.isValidElement(<Foo />));
. Basically, you get an element when you callReact.createElement(Foo)
, which is what<Foo />
is doing under the hood. – Felix Kling Commented Sep 26, 2017 at 17:56Foo
orBar
and pass additional props to?React.cloneElement
returns error – Kousha Commented Sep 26, 2017 at 17:59