[英]Render a variable in React html
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>
)
};
I am trying to render the time in the text tag but it keep throwing error.我正在尝试在文本标签中呈现时间,但它不断抛出错误。 How do I resolve this issue.我该如何解决这个问题。 This is under react framework.这是在反应框架下。
The getTime
function should return a string and not an object, and you should call it in the JSX - getTime()
: getTime
function 应该返回一个字符串而不是 object,你应该在 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>
SInce you didn't share the error I'm going to guess it's because you return a function in your JSX:既然您没有分享错误,我猜这是因为您在 JSX 中返回了 function:
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>
)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.