You need to enable JavaScript to run this app. React父子组件传值报错:TypeError无法读取null的items属性
优惠活动
大模型
产品
解决方案
定价
更多

React父子组件传值报错:TypeError无法读取null的items属性

React类组件父传子通信错误修复

报错根源

  • 子组件读取状态方式错误:Clock2 没有定义自身的 state,items 属于父组件 Clock 的内部状态,必须通过 props 传递获取,当前写法直接读取 this.state.items 会得到空值,触发报错。
  • 父组件传参命名不匹配:父组件给子组件传值时,props 属性名写为 Clock2,和子组件预期读取的 items 字段完全不对应。
  • 事件方法未正确传递:父组件的 Add 方法没有作为 props 传入子组件,且未绑定 this 上下文,即使子组件按钮绑定也无法执行逻辑。

修复后可运行代码

class Clock extends React.Component {
  state = { items: ["Hakob", "Arman"] };

  // 箭头函数定义自动绑定当前组件 this
  Add = () => {
    const newItem = prompt("请输入新增内容");
    const newItems = this.state.items.concat([newItem]);
    this.setState({ items: newItems });
  }

  render() {
    return (
      <div>
        {/* 按语义化命名传递 props */}
        <Clock2 items={this.state.items} onAdd={this.Add} />
      </div>
    );
  }
}

class Clock2 extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.props.onAdd}>click</button>
        {/* 从 props 读取父组件传入的状态 */}
        {this.props.items.map((e, i) => <div key={e + i}> {e} </div>)}
      </div>
    );
  }
}

ReactDOM.render(<Clock />, document.body);

原有 HTML 中引入的 React 16.6.3 相关依赖无需修改,直接保留即可正常运行。


内容的提问来源于stack exchange,提问作者Hayko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.20 01:15:05