首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在React中重新呈现之前预先计算JSX变量

在React中重新呈现之前预先计算JSX变量
EN

Stack Overflow用户
提问于 2017-07-20 16:18:43
回答 1查看 639关注 0票数 2

在调用re-render()函数之前,是否可以使用react准备一个变量以在JSX中显示?

例如:

代码语言:javascript
运行
复制
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()函数中更新这个变量,因为我需要在每次重新渲染时刷新它,而渲染函数只被调用一次。我不能使用状态变量,否则我会得到一个无限循环的重新渲染。

EN

回答 1

Stack Overflow用户

发布于 2021-03-20 19:48:40

打字脚本

代码语言:javascript
运行
复制
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);
代码语言:javascript
运行
复制
<Variable value={price * quantity} render={amount =>
  <p>
    Amount: {amount} {plural('coin', amount)}
  </p>
} />

Javascript

代码语言:javascript
运行
复制
const props => props.render(props.value);
代码语言:javascript
运行
复制
<Variable value={price * quantity} render={amount =>
  <p>
    Amount: {amount} {plural('coin', amount)}
  </p>
} />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45209193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档