我是React JS的新手,所以我为这种类型的错误表示了歉意,在这里我创建了2个类Test1和Test2,我想从类1调用function_two
函数,但它不起作用,谁能帮我解决这个问题,这是我的完整代码
class Test1 extends React.Component {
function_one() {
<Test2 function_two={this.function_two} />
}
render() {
return (
<h1>{this.function_one}</h1>
);
}
}
class Test2 extends React.Component {
function_two() {
return "Funtion 2";
}
}
//CallCRUD
ReactDOM.render(
<Test1 />, document.getElementById('root')
);
答案 0 :(得分:1)
两件事:
this.function_one
应该是this.function_one()
function_one
中返回任何内容(您忘记了return语句)工作修复:
class Test1 extends React.Component {
function_two(origin) {
console.log('Hello, from ' + origin)
}
function_one() {
return <Test2 function_two={this.function_two} />
}
render() {
return (
<h1>{this.function_one()}</h1>
);
}
}
class Test2 extends React.Component {
componentDidMount() {
this.props.function_two('Test2')
}
render = () => <div/>
}
ReactDOM.render(
<Test1 />, document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.production.min.js"></script>
<div id='root'/>
编辑:
如果您的目标只是在h1
标记中呈现某些内容,则可以执行以下操作:
class Test1 extends React.Component {
function_one() {
return <Test2/>
}
render() {
return (
<h1>{this.function_one()}</h1>
);
}
}
class Test2 extends React.Component {
render(){
return <div>Hi, I'm Test2</div>
}
}
ReactDOM.render(
<Test1 />, document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.production.min.js"></script>
<div id='root'/>
更短的语法:
const Test1 = () => <h1><Test2/></h1>
const Test2 = () => <div>Hi, I'm Test2</div>
ReactDOM.render(
<Test1 />, document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.production.min.js"></script>
<div id='root'/>