我是 React 新手,抱歉,如果我没有记下术语。
我接受了一些工作来更改现有的 React 组件并更新它显示的值。
现在,渲染函数返回一个包含一堆数据的对话字段:
render() {
const { selectedDate, labelText, dialogTitle, ...props } = this.props
return (
<DialogField
name="dialog-field"
labelText={floatingLabelText}
dialogTitle={dialogTitle}
errorText="Please check your selection"
userFriendlyValue={
selectedDate
? [this.dateUtil.translateMonthShort(selectedDate.getMonth()), selectedDate.getFullYear()].join(' ')
: ''
}
>
</DialogField>
)
我想采用 userFriendlyValue 中的函数并将其抽象为自己的独立函数。为此,我在渲染函数上方添加了以下内容:
userFriendlyDate() {
selectedDate
? [this.dateUtil.translateMonthShort(selectedDate.getMonth()), selectedDate.getFullYear()]
.join(' ')
: 'ERROR'
}
在我的constructor()
中添加了这个:
this.userFriendlyDate = this.userFriendlyDate.bind(this)
并更新了返回的元素:
return (
<DialogField
name="dialog-field"
labelText={floatingLabelText}
dialogTitle={dialogTitle}
errorText="Please check your selection"
userFriendlyValue={this.userFriendlyDate}
>
</DialogField>
)
但这行不通。它不会抛出任何错误,但也不显示任何值。
有人知道我做错了什么以及我应该如何抽象这个函数吗?
最佳答案
您没有在函数中返回任何值。
userFriendlyDate() {
return selectedDate
? [this.dateUtil.translateMonthShort(selectedDate.getMonth()), selectedDate.getFullYear()]
.join(' ')
: 'ERROR'
}
我认为你应该调用它,而不是绑定(bind)它。
userFriendlyValue={this.userFriendlyDate()}
关于javascript - react : how to move a function out of the render() function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57864439/