编程语言
首页 > 编程语言> > javascript-如何解构{this.props.children}?

javascript-如何解构{this.props.children}?

作者:互联网

我想为我的移动应用添加背景,但是当我使用“ this.props.children”时
埃斯林特说我“必须使用破坏性道具分配”.为什么我可以破坏这个道具?

这是我的代码,

export default class WallPaper extends Component {
  render() {
    return (
      <ImageBackground
        source={backgroundimg}
        imageStyle={{ opacity: 0.9 }}
        style={styles.container}
      >
        {this.props.children}
      </ImageBackground>
    );
  }
}

当我使用此代码

export default class WallPaper extends Component {
  render() {
    const { children } = this.props;
    return (
      <ImageBackground
        source={backgroundimg}
        imageStyle={{ opacity: 0.9 }}
        style={styles.container}
      >
        {children}
      </ImageBackground>
    );
  }
}

我遇到此错误“道具验证中缺少’儿童’”
error

当我使用此代码时,

export default class WallPaper extends Component {
  render() {
     (this.props) => {
    return (
      <ImageBackground
        source={backgroundimg}
        imageStyle={{ opacity: 0.9 }}
        style={styles.container}
      >
        {props.children}
      </ImageBackground>
    );
    }
  }
}

我有这个错误,
enter image description here

预先感谢您的帮助 !

解决方法:

您可以尝试以下操作以从this.props中破坏子级:

export default class WallPaper extends Component {
  render() {
    const { children } = this.props;

    return (
      <ImageBackground
        source={backgroundimg}
        imageStyle={{ opacity: 0.9 }}
        style={styles.container}
      >
        {children}
      </ImageBackground>
    );
  }
}

看起来您的项目可能需要此组件的propTypes.尝试以下操作添加子道具类型.注意,您将需要安装软件包prop-types

// ... 
import PropTypes from 'prop-types';

class WallPaper extends Component {      
  render() {
    const { children } = this.props;

    return (
      <ImageBackground
        source={backgroundimg}
        imageStyle={{ opacity: 0.9 }}
        style={styles.container}
      >
        {children}
      </ImageBackground>
    );
  }
}

WallPaper.propTypes = {
  children: PropTypes.node // or PropTypes.node.isRequired to make it required
};

export default WallPaper;

希望有帮助!

标签:destructuring,reactjs,node-js,react-native,javascript
来源: https://codeday.me/bug/20191108/2007248.html