gpt4 book ai didi

javascript - 在 React html 中渲染变量

转载 作者:行者123 更新时间:2023-11-28 16:57:56 24 4
gpt4 key购买 nike

const getTime = () => {
const today = new Date();
const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
return {time};
}

export default function UpdateButton() {
const classes = useStyles();
const today = new Date();
const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
return (
<div>
<Button variant="contained" className={classes.button}>
Update
</Button>
<text>Last Updated: {getTime}</text>
</div>
)
};

我试图在文本标记中渲染时间,但它一直抛出错误。我该如何解决这个问题。这是在react框架下。

最佳答案

getTime 函数应该返回一个字符串而不是一个对象,您应该在 JSX 中调用它 - getTime():

const getTime = () => {
const today = new Date();
const time = today + ' ' + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
return time;
}

function UpdateButton() {
return (
<div>
<button variant="contained">
Update
</button>
<text>Last Updated: {getTime()}</text>
</div>
)
};

ReactDOM.render(
<UpdateButton /> ,
root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

关于javascript - 在 React html 中渲染变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58574853/

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