我有一个子组件和一个父组件。我在子组件中有一个函数,它返回一些 jsx 我想做的是使用该函数在父组件中返回相同的 jsx 但我无法找到一种方法来做到这一点。我给出了我的最小代码:
父组件:
class App extends Component {
render() {
return (
<div className="App">
<Player ref={instance=>{this.player = instance}} />
{this.player.func('aaa.com','bbb')}
</div>
);
}
}
export default App;
子组件:
import React, { Component } from "react";
class Player extends Component {
func = (url, label) => {
return (
<button onClick={() => this.func(url)}>
{label}
</button>
)
}
render() {
return <div>1</div>;
}
}
export default Player;
Error: Cannot read property 'func' of undefined
//
Note: i know i can use the jsx in parent component by copy-pasting but iam trying to figure out a way of doing like this. I am having doubt that is it even possible
最佳答案
您可以创建一个 Player
对象并使用该对象访问该函数。
new Player().func('aaa.com','bbb')
关于javascript - 如何在父组件中渲染子组件函数的jsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50939927/