![](/img/trans.png)
[英]How to pass props through this.props.children() not this.props.children
[英]How i can destructuring {this.props.children}?
我想为我的移动应用程序添加背景,但是当我使用“this.props.children”时,eslint 说我“必须使用解构道具分配”。 为什么我可以解构这个道具?
这是我的代码,
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> ); } }
当我使用此代码时,
export default class WallPaper extends Component { render() { (this.props) => { return ( <ImageBackground source={backgroundimg} imageStyle={{ opacity: 0.9 }} style={styles.container} > {props.children} </ImageBackground> ); } } }
预先感谢您的帮助 !
功能组件案例缺少答案。 孩子只是传递给组件的道具。 为了像使用 props.url 一样使用它,您需要将它添加到该列表中,以便它可以从 props 对象中“拉出”。
export const Welcome = ({name, hero, children}) => {
return (
<div>
<h1> Class Component with {name} as {hero} </h1>
{children}
</div>
)
}
您可以尝试以下方法来this.props
children
:
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。 请尝试以下操作添加children
道具类型。 注意,您需要安装包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;
希望这有帮助!
这是由于linting规则 。
如果您不想破坏,可以关闭规则。
如果你想要,你可以这样做。
export default class WallPaper extends Component {
render() {
const {children} = this.props
return (
<ImageBackground
source={backgroundimg}
imageStyle={{ opacity: 0.9 }}
style={styles.container}
>
{this.props.children}
</ImageBackground>
);
}
}
export default class WallPaper extends Component {
render() {
(this.props) => {
return (
<ImageBackground
source={backgroundimg}
imageStyle={{ opacity: 0.9 }}
style={styles.container}
>
{props.children}
</ImageBackground>
);
}
}
}
对于类组件:
export class Welcome extends Component {
render(){
const {name, hero, children} = this.props
return (
<div>
<h1> Class Component with {name} as {hero} </h1>
{children}
</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.