Javascript 将本机保留日期作为类组件中的状态进行反应
我仍然熟悉React Native,所以我只希望我的类组件Date返回一个显示当前月份的文本组件。但是,我对如何将以下代码实质性地合并到我的类组件中感到困惑:Javascript 将本机保留日期作为类组件中的状态进行反应,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我仍然熟悉React Native,所以我只希望我的类组件Date返回一个显示当前月份的文本组件。但是,我对如何将以下代码实质性地合并到我的类组件中感到困惑: var date = new Date(); var month = date.getMonth(); 以便我可以在文本标记中使用月份: class Date extends Component { state = {month: /*new Date().getMonth() ???*/} render(props) {
var date = new Date();
var month = date.getMonth();
以便我可以在文本标记中使用月份:
class Date extends Component {
state = {month: /*new Date().getMonth() ???*/}
render(props) {
return (
<Text style={{ marginBottom: 10 }}> Budget for {month} </Text>
);
}
}
类日期扩展组件{
状态={月份:/*新日期().getMonth()???*/}
渲染(道具){
返回(
{月}预算
);
}
}
试试这个
class Date extends Component {
state = {month:''}
componentDidMount(){
const month = new Date().getMonth() + 1;
this.setState({ month });
}
render(props) {
return (
<Text style={{ marginBottom: 10 }}> Budget for {this.state.month} </Text>
);
}
}
类日期扩展组件{
状态={月份:'}
componentDidMount(){
const month=新日期().getMonth()+1;
this.setState({month});
}
渲染(道具){
返回(
{this.state.month}的预算
);
}
}
Try.toString()作为{month.toString()},因为Date是一个对象。您可以使用“时刻”或“日期”fns将其转换为更加用户友好的格式。