简体   繁体   English

React-对象作为React子对象无效

[英]React - objects are not valid as a React child

I am trying to create the stop watch on the reactive js. 我正在尝试在反应式js上创建秒表。 Below is my code 下面是我的代码

 <div id="root"></div> <script src="https://unpkg.com/react@16.3.1/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.3.1/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script> <script src="https://unpkg.com/prop-types@15.6.1/prop-types.js"></script> <script type="text/babel"> function StopWatch(running, lapse) { const buttonStyles = { border: "1px solid #ccc", background: "#fff", fontSize: "2em", padding: 15, margin: 5, width: 200 }; return ( <div> <label style={{ fontSize: "5em", display: "block" }} > {lapse}ms </label> <button style={buttonStyles}>{running ? "stop" : "start"}</button> <button style={buttonStyles}>Clear</button> </div> ); } const rootElement = document.getElementById("root"); const element = <StopWatch running={true} lapse={0} />; ReactDOM.render(element, rootElement); </script> 

While executing above file, i am getting the error message: 在执行上述文件时,我收到错误消息:

Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {}). 未捕获的不变违规:对象作为React子对象无效(找到:带有键{}的对象)。 If you meant to render a collection of children, use an array instead. 如果要渲染子级集合,请改用数组。

My concern is that I am able to pass the value for the property running , but the error happen when I am passing the value for the property lapse . 我担心的是,我能够传递运行中的属性的值,但传递属性失效的值时会发生错误。 What is the issue here and what is the difference on passing the value for both properties? 这里的问题是什么,传递两个属性的值有什么区别?

Your functional Component receives props as the first argument. 您的功能组件将props作为第一个参数。

It should be something like this with object destructuring 对象解构应该是这样的

<script type="text/babel">
function StopWatch({ running, lapse }) {
  const buttonStyles = {
    border: "1px solid #ccc",
    background: "#fff",
    fontSize: "2em",
    padding: 15,
    margin: 5,
    width: 200
  };
  return (
    <div>
      <label
        style={{
          fontSize: "5em",
          display: "block"
        }}
      >
        {lapse}ms
      </label>

      <button style={buttonStyles}>{running ? "stop" : "start"}</button>
      <button style={buttonStyles}>Clear</button>
    </div>
  );
}
const rootElement = document.getElementById("root");
const element = <StopWatch running={true} lapse={0} />;
ReactDOM.render(element, rootElement);

</script>

You forgot to put the curly brackets while passing the props; 您在传递道具时忘了放大括号; it should be: 它应该是:

function StopWatch({ running, lapse })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM