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>
)
};
我正在尝试在text标签中渲染时间,但是它一直抛出错误。我该如何解决此问题。这是在react框架下。
答案 0 :(得分:2)
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>
答案 1 :(得分:1)
由于您没有共享错误,所以我猜这是因为您在JSX中返回了一个函数:
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>
)
};