代码之家  ›  专栏  ›  技术社区  ›  Nikul Panchal

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

  •  0
  • Nikul Panchal  · 技术社区  · 7 年前

    我是react js的新手,所以我为这种类型的错误道歉,这里我创建了两个类,Test1和Test2,我想调用 function_two 来自类1的函数,但它不工作,有人能帮我解决这个问题吗,这是我的完整代码

    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 回复  |  直到 7 年前
        1
  •  2
  •   Treycos    7 年前

    两件事:

    1. 您忘记调用您的函数: this.function_one 应该是 this.function_one()
    2. function_one (您忘记了返回语句)

    工作修复:

    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')
    );
    <脚本src=”https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.production.min.js“></脚本>
    <脚本src=”https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.production.min.js“></脚本>
    <div id='root'/>

    较短的语法:

    const Test1 = () => <h1><Test2/></h1>
    
    const Test2 = () => <div>Hi, I'm Test2</div>
    
    ReactDOM.render(
    	<Test1 />, document.getElementById('root')
    );
    <脚本src=”https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.production.min.js“></脚本>
    <脚本src=”https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.production.min.js“></脚本>
    <div id='root'/>