当一些道具值满足时,我需要在每个孩子之间添加元素 怎么做
“仅在prop值为space时添加元素”
现在我确实喜欢这样
const style={
height:"10px"
}
if(this.props.space){
style.width=30;
}
render(){
return(
{React.Children.map(children, (child, i) => {
return (
<React.Fragment>
<span style={style}></span>
<React.Fragment>{child}</React.Fragment>
</React.Fragment>
);
})}
)
}
答案 0 :(得分:0)
那么,只有空格为真时,您才需要跨度吗?
那么你可以做这样的事情
{React.Children.map(children, (child, i) => {
return (
<React.Fragment>
{this.props.space && <span style={style}></span>}
<React.Fragment>{child}</React.Fragment>
</React.Fragment>
);
})}
此处介绍了该概念https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator
它之所以有效,是因为true && expression
将计算为表达式,而false && expression
将计算为false。
答案 1 :(得分:0)
Span是一个内联元素,不需要width and height
。您可以改为有条件地返回div元素,然后像
function App({ children, space }) {
const style = {
height: "10px",
width: "30px",
backgroundColor: "red",
display: "inlin"
};
return (
<React.Fragment>
{React.Children.map(children, (child, i) => {
return (
<React.Fragment>
<div style={{ display: "flex" }}>
{space ? <div style={style} /> : null}
<div>{child}</div>
</div>
</React.Fragment>
);
})}
</React.Fragment>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<App space>
<div>Hello</div>
</App>,
rootElement
);
但是,有条件地添加元素以在左侧提供空间似乎不是一个好主意。您可以改为添加类和添加属性,例如margin-left或添加样式
return (
<React.Fragment>
{React.Children.map(children, (child, i) => {
return (
<React.Fragment>
<div style={{marginLeft: '30px'}}>{child}</div>
</React.Fragment>
);
})}
</React.Fragment>
);