在调用re-render()函数之前,是否可以使用react来准备要在JSX中显示的变量?
例如:
count_function() {
e.g.
return number_of_children_having_state_#
}
a_prerender_function() { // Which one componentWillUpdate ?? But in that case, how to pass it to the render function
// const count = this.count_function() // This can't be put in state, otherwise 'infinite-loop'
}
render () {
// const count = this.count_function() // This is only called at the first render! But not on next re-render
return (
<div>
{count}
</div>
)
}
我无法在render()函数中更新此变量,因为我需要在每次重新渲染时刷新它,并且渲染函数只调用一次。 我不能使用状态变量,否则我会得到一个无限循环的重新渲染。
答案 0 :(得分:0)
打字稿
interface Props<T> {
value: T;
render: (value: T) => JSX.Element;
}
type IVariable = <T>(props: Props<T>) => JSX.Element;
const Variable: IVariable = props => props.render(props.value);
<Variable value={price * quantity} render={amount =>
<p>
Amount: {amount} {plural('coin', amount)}
</p>
} />
Javascript
const props => props.render(props.value);
<Variable value={price * quantity} render={amount =>
<p>
Amount: {amount} {plural('coin', amount)}
</p>
} />