简体   繁体   中英

React - objects are not valid as a React child

I am trying to create the stop watch on the reactive 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 {}). 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.

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 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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