我有一个这样的组件
class Hourly extends Component {
render() {
return (
<div key={this.props.key} id={this.props.id} className="col-xs-3 text-center vcenter box parent">
<div className="child">
<div>{this._theDay(this.props.day)}</div>
<div>{this.props.summary}</div>
</div>
</div>
);
}
}
我想在组件中使用自定义函数 (_theDay),稍后我会在另一个组件中使用该函数
自定义函数:
_theDay(time) {
moment.locale('en-gb');
var dateTime = moment(time*1000).format('dddd');
return dateTime;
}
我稍后调用该组件
<Hourly
key={hour.time}
id={hour.time}
day={hour.time}
summary={hour.summary}
/>
但是我收到错误:Uncaught (in promise) DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.(…)
当我只使用<div>{this.props.day}</div>;
时一切正常,但我无法使用我的自定义函数
最佳答案
我认为这与 React 在 props 更改后尝试更新 DOM 有关。尝试使用 <div/>
上的按键绑定(bind)到props.day
帮助它知道 children 已经改变。
class Comp extends React.Component {
render() {
let day = this._theDay(this.props.day)
return <div key={day}>{day}</div>;
}
}
关于javascript - 在 React 中使用自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793494/