【问题标题】:Child(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return nullChild(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null
【发布时间】:2018-08-20 11:49:34
【问题描述】:

我有两个 js 文件 Child.js 和 App.js。

Child.js

import React from 'react';

const Child = (props) =>{
    <div>
        <button onClick={props.doWhatever}>{props.title}</button>
    </div>

}
export default Child;

App.js

import React, { Component } from 'react';
import './App.css';
import Child from './components/parentTochild/Child.js'

class App extends Component {
  state = {
    title : 'Helloooo'
  }

  changeWorld = (newTitle) => {
    this.setState = ({
      title : newTitle
    });
  }

  render() {
    return (
      <div className="App">
        <Child doWhatever={this.changeWorld.bind(this , 'New world')} title={this.state.title}/>
      </div>
    );
  }
}
export default App;

在执行此代码时,我收到了标题中提到的错误。我试图解决它。但我无法弄清楚这段代码有什么问题。

当我删除 &lt;Child doWhatever={this.changeWorld.bind(this , 'New world')} title={this.state.title}/&gt; 并键入它显示在屏幕上的文本时。问题在于使用 Child 组件时。

【问题讨论】:

  • 你需要在Child添加return语句或者使用隐式return const Child = props =&gt; ( /* notice ( not {*/ &lt;div&gt;
  • 必须在 Child.js 中包含 return 语句

标签: reactjs parent-child


【解决方案1】:

你应该从子组件返回一些东西。

import React from 'react';

const Child = (props) =>{
    return (
          <div>
               <button onClick={(event)=>props.doWhatever('New world')}>{props.title}</button>
          </div>
    );

}
export default Child;

更新:

如果您想通过事件处理程序向您发送文本,可以这样做:

import React, { Component } from 'react';
import './App.css';
import Child from './components/parentTochild/Child.js'

class App extends Component {
  constructor(props){
      super(props);
      this.state={
          title : 'Helloooo'
      };
      this.changeWorld=this.changeWorld.bind(this);
  }

  changeWorld = (newTitle) => {
    this.setState = ({
      title : newTitle
    });
  }

  render() {
    return (
      <div className="App">
        <Child doWhatever={this.changeWorld} title={this.state.title}/>
      </div>
    );
  }
}
export default App;

【讨论】:

  • 谢谢。错误得到解决。但是 onClick 事件不起作用
  • 将 this 用于构造函数 => constructor() { this.changeWorld = this.changeWorld.bind(this); } 和 this 用于调用子组件 =>
  • 把函数changeWorld里面的代码改成this.setState({ title : newTitle });。因为 setState 是一个函数,所以不能将值作为变量赋值
  • 我需要通过函数“changeWorld”传递值“新世界”。@jsDevia 正如你所说的尝试 construstor 。但是如何传递这个值呢?
  • 我更新了答案,也许它可以帮助你,请注意我从子组件发送新文本,但如果你需要从其更高组件传递文本,请告诉我。
猜你喜欢
  • 2018-12-08
  • 2021-05-13
  • 2019-08-14
  • 1970-01-01
  • 2018-03-26
  • 2020-07-06
  • 2022-01-12
  • 2021-05-15
  • 2021-03-05
相关资源
最近更新 更多