从父组件传递给子组件的道具未定义

时间:2021-04-16 10:05:04

标签: react-native

我正在尝试通过道具将布尔值从父级传递给子级。 在父组件中:

class Parent extends Component {
      constructor(props) {
          super(props);
        }
        ...
        render() {
          ...
          retrun (
          <Child
            addSearchBar
            value="child 1"
          />
          <Child
            value="child 2"
          />
          );
        }
    }

我尝试执行此操作 addSearchbar={true},但出现 ESLint 错误 ESLint: Value must be omitted for boolean attributes。 在 Child 组件 中,当我尝试 console.log 时,道具 addSearchbar 不在道具内,它的值为 undefined。我如何传递布尔值?

class Child extends Component {
  constructor(props) {
      super(props);
      console.log(this.props) <-- addSearchbar isn't within the props

      this.state = {
        searchText: '',
      };
    }
    ...
    render() {
      const {
        addSearchbar
      } = this.props;
      
      console.log(addSearchbar) <--undefined
      
      ...
    }
}

1 个答案:

答案 0 :(得分:0)

对于布尔属性,您不必提供值。

如果不传递prop,则值为false

<Child/>

如果传递prop,则值为true

<Child addSearchbar/>

我创建了一个基本的 working example on codepen