javascript - react 子 JSX 元素不从父级继承

标签 javascript reactjs react-native

感觉我的问题很简单,但我不明白为什么它不起作用。

为什么我要尝试做一些基本的事情——我将一个函数从父级传递给子级,它应该将父级的“测试”值的值(这只是一个概念证明)增加 1。问题调用父函数时发生。我收到“无法读取未定义的属性测试”。在调试器中,this.props 也是未定义的,所以 this.props.test 将是不足为奇的。我错过了什么?

家长:

export default class GameList extends Component {
  constructor({ navigation }) {
    super();
    this.state = {
      test: 0,
    }
  };


  updateState() {
    this.setState({
      test: this.state.test++,
    });
  }

  render() {
    return (
     <View style={styles.background}>
        <Header updateState={this.updateState} />   
     </View >
    )
  }
}

child :

import React, { Component } from 'react';
import { View, TextInput } from 'react-native';

import styles from './styles';

class Header extends Component {
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={styles.input}
          placeholder="Search..."
          onChangeText={(text) => {
            this.props.updateState();
          }}
        />
      </View>
    );
  }

  filterRows(searchText, dataSet) {
    return dataSet.filter((record) => record.title.includes(searchText));
  }
}


export default Header;

最佳答案

有两个问题:

  • 在您的构造函数中绑定(bind)该方法,为其提供正确的上下文。关于为什么这是必要的更多信息在 React documentation under Handling Events 中。 .
  • 不要在状态属性上使用 ++,因为它会修改原始状态,并且在检查是否重新渲染时可能会破坏任何比较(即 this.state.test === newState.test? 是的,因为原来的已经改了)。在 React documentation under Component 下有更多信息,请注意他们如何使用 quantity: state.quantity + 1 而不是 quantity: state.quantity++

所以你得到:

export default class GameList extends Component {
  constructor({ navigation }) {
    super();
    this.state = {
      test: 0,
    }
    this.updateState = this.updateState.bind(this); // Bind to the correct context
  };


  updateState() {
    this.setState({
      test: this.state.test + 1, // Do not mutate the original state
    });
  }

  render() {
    return (
     <View style={styles.background}>
        <Header updateState={this.updateState} />   
     </View >
    )
  }
}

关于javascript - react 子 JSX 元素不从父级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708996/

相关文章:

Javascript - react native 。调用 Render() 函数时,子组件(动态列表)不呈现

javascript - React Native 中组件之间的通信(子 -> 父)

javascript - 独立 js-cookie javascript 库中的 "Cookies not defined"?

javascript - 如何在 JavaScript 中使用 Skycons 两次使用 id

javascript - 颜色不会在 div 上改变,由脚本生成

javascript - 如何在组件之外设置状态?

reactjs - 在 React Native 中使用 useContext 的上下文 API 显示 TypeError

javascript - 解构赋值与 async/await 不同吗?

reactjs - useContext() 不应该只用于低频率更新吗? (mobx-react-lite)

javascript - 嵌套 HTML 元素上的 onKeyDown