首页 > 解决方案 > 从组件中的函数渲染值

问题描述

我在 React 中有一个这样的组件:

const myAge = () => {
  var diff = Date.now() - new Date(1991, 2, 1);
  var age = new Date(diff);
  return age;
};
export const About = (props) => {
  return (
      <Container id={props.id}>
         <p> My age is: {myAge}</p>
      </Container>
  )
}

我希望myAge在标签中返回并呈现函数的结果p,但没有呈现任何内容。我不知道我做错了什么,有什么建议吗?泰。

标签: reactjs

解决方案


您必须调用该函数,即{myAge()} 然后 thenew Date(diff)不是字符串,因此您必须像这样强制转换它return String(age)


推荐阅读