函数不会在React js中从一个类调用到另一个类

时间:2019-01-09 10:40:36

标签: reactjs

我是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')
);

1 个答案:

答案 0 :(得分:1)

两件事:

  1. 您忘记了调用函数:this.function_one应该是this.function_one()
  2. 您没有在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'/>