gpt4 book ai didi

javascript - react : Call a function from inside render function

转载 作者:行者123 更新时间:2023-11-30 15:30:15 25 4
gpt4 key购买 nike

我提到了几个类似的问题,但我的情况略有不同。

Call a React Function from inside Render

How to Call a Function inside a Render in React/Jsx

React: Cant call a function inside child component

export default class CodeEditor extends React.Component {

appendAssets(asset) {
console.log(asset)
this.refs.editor.editor.insert(`player.asset('${asset}')`)
this.refs.editor.editor.focus()
}


render() {
function sequenceHierarchy (data, outputArray) {
level++
data.forEach(function (asset){
outputArray.push(<li className={`level_${level}`}><button onClick={_ => this.appendAssets(asset.name)}>{asset.name}</button></li>)
if(asset.children.length) {
sequenceHierarchy(asset.children, outputArray)
}
})
level--
}
}

}

因此 sequenceHierarchy 函数中按钮的 onClick 必须调用 appendAssets。当然,因为 this 不能调用它,因为它不是这个组件的一部分,我也尝试过只使用 appendAssets(asset.name),但仍然如此给出错误 Uncaught ReferenceError: appendAssets is not defined

最佳答案

我强烈建议您阅读这篇 answer用于理解 this 关键字及其在函数内的行为。

引用链接的答案:

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables.

(请在继续之前阅读整个链接的答案)

您可以设置对引用正确this 的变量的引用。看这个JSFiddle

let that = this; // assign this reference to variable that.
function sequenceHierarchy (data, outputArray) {
data.forEach((item) => {
outputArray.push(
<li>
<button onClick={that.appendAssets.bind(this, item)}>
Append {item}
</button>
</li>
);
})
}

您可以使用 bind方法来设置正确的 this,同时调用 sequenceHierarchy 函数,如下所示。看这个JSFiddle

{sequenceHierarchy.bind(this, (['1', '2', '3'], []))} 

您可以使用 ES6 arrow function像这样调用 sequenceHierarchy 函数。

{() => {sequenceHierarchy(['1', '2', '3'], [])}} 

以上所有方法都可以正常工作。

希望这有帮助:)

关于javascript - react : Call a function from inside render function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42372269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com