反应,将文本动态添加到参考范围

时间:2018-09-01 18:44:28

标签: reactjs ref

我正在尝试将消息呈现给特定于列表中某个项目的span标签。我已经阅读了很多有关React'refs'的文章,但无法弄清楚在引用该消息后如何用该消息填充跨度。

因此有一个项目列表,每个项目行都有自己的按钮,该按钮会触发具有与该项目相关联的ID的API。根据API响应,我想使用响应消息更新span标签,但仅针对该项目

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

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

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

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

3 个答案:

答案 0 :(得分:2)

我建议使用状态。因为字符串引用旧版(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
    })
}

答案 1 :(得分:1)

已将解决方法设置为innerText

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

但不要使用ref来更新{render}中的元素。

答案 2 :(得分:0)

我现在正面临着这个问题,我是这样想的:

// 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

请注意,此后我们不使用.来调用引用,也不使用refs来实现我们想要的。
我只是猜测this应该是一个可以保存当前对象内部变量的对象。然后,因为ref在该对象的内部,那么我们应该能够使用上面的动态值来调用它...

我可以说它自动运行了!

相关问题