【问题标题】:React, dynamically add text to ref spanReact,动态添加文本到 ref span
【发布时间】:2018-09-01 18:44:27
【问题描述】:

我正在尝试将消息呈现给特定于列表中项目的跨度标记。我已经阅读了很多关于 React 'refs' 的内容,但不知道如何在消息被引用后填充 span。

所以有一个项目列表,每个项目行都有自己的按钮,该按钮会触发一个带有与该项目关联的 id 的 API。根据 API 响应,我想用响应消息更新 span 标签,但仅限于该项目

当列表被创建时,项目被循环遍历并且每个项目都包含这个

<span ref={'msg' + data.id}></span><Button onClick={() => this.handleResend(data.id)}>Resend Email</Button>

在 API 调用之后,我想引用特定的 span 并在其中呈现正确的消息。但我无法弄清楚如何在代码的这一点上渲染到跨度。我知道这行不通,但这本质上是我想要做的。有什么想法吗?

if (response.status === 200) {
    this.refs['msg' + id] = "Email sent";

【问题讨论】:

  • 为什么不使用state??? if (response.status === 200)this.setState({...})

标签: reactjs ref


【解决方案1】:

我建议使用状态。因为字符串 refs legacy (https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)

const msgs = [
    { id:1, send:false },
    { id:2, send:false },
    { id:3, send:false },
];

this.state = {
    msgs
};

return this.state.msgs.map((msg, index) => {
    const status = msg.send ? "Email Sent" : "";
    <span>{ status }</span><Button onClick={() => this.handleResend(index)}>Resend Email</Button>
});

async handleResend (index) {
    const response = await callAPI(...);
    if(reponse.status !== 200) return;

    const newMsgs = _.cloneDeep(this.state.msgs);
    newMsgs[index].send = true;
    this.setState({
        msgs: newMsgs
    })
}

【讨论】:

    【解决方案2】:

    解决方法设置为innerText

       this.refs['msg' + id].innerText = "Email sent";
    

    但不要使用ref,而是尝试使用state 来更新渲染中的元素。

    【讨论】:

    • 是的,我想到了状态,但不知道如何使用状态来引用项目
    【解决方案3】:

    我现在正面临这个问题,我是这样解决的:

    // currentQuestion is a dynamic Object that comes from somewhere and type is a value
    const _target = `${currentQuestion.type}_01` 
    const _val = this[`${_target}`].current.clientHeight // here is the magic
    

    请注意,在此之后我们不使用 . 来调用 ref 并且不使用 refs 来实现我们想要的。
    我只是猜想this 应该是一个保存当前对象内部变量的对象。那么由于ref 在该对象内部,那么我们应该能够使用像上面这样的动态值来调用它...

    我可以说它自动运行!

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多