gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:08:10 24 4
gpt4 key购买 nike

我正在尝试在响应式(Reactive) js 上创建秒表。下面是我的代码

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

执行上述文件时,我收到错误消息:

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.

我担心的是,我能够传递属性正在运行的值,但是当我传递属性失效的值时会发生错误。这里有什么问题以及传递两个属性的值有什么区别?

最佳答案

您的功能组件接收 props 作为第一个参数。

应该是这样的 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>

关于javascript - React - 对象作为 React 子对象无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55206151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com