我看起来像dump component
export default class DumpComponent extends Component {
renderSomething(something) {
console.log(something)
}
render() {
return (
<div>
{ this.renderSomething(something) }
</div>
);
}
}
我包含在container
export default class Container extends Component {
...
render() {
<DumpComponent
// call function renderSomething() with a variable I pass from here
/>
}
我如何使用renderSomething()
中声明的变量Container
调用函数container
?
答案 0 :(得分:0)
使用子componentDidMount从父级和调用函数中获取prop。
class Child extends React.Component {
componentDidMount() {
this.method(this.props.val);
}
method(val) {
console.log(val)
}
render() {
return <h1>Hello World!</h1>
}
}
class Parent extends React.Component {
render() {
return (
<div>
<Child val='hello' />
</div>
);
}
}
演示:https://jsfiddle.net/v123582/25ebngdd/
此外,它可以在render()
上调用函数class Child extends React.Component {
method(val) {
alert(val);
}
render() {
return <div>{ this.method(this.props.val) }</div>
}
}
class Parent extends React.Component {
render() {
return (
<div>
<Child val='hello' />
</div>
);
}
}
答案 1 :(得分:0)
一路:
export default class DumpComponent extends Component {
renderSomething(something) {
console.log(something)
}
render() {
return (
<div>
{ this.renderSomething(this.props.something) }
</div>
);
}
}
export default class Container extends Component {
...
render() {
<DumpComponent
something="The thing"
/>
}
导出函数togather with component在您的情况下可能很有用:
# DumpComponent .js
export default class DumpComponent extends Component {
}
export const doSomething(something) {
console.log(something)
}
# Container.js
import DumpComponent, {doSomething} from 'DumpComponent'
class Container extends Component {
render() {
<DumpComponent
something={doSomething("The thing")}
/>
}