2 回答
TA贡献1845条经验 获得超8个赞
如果您以React现在的方式使用组件初始化变量(const leftIcon = <SmallIcon />),那么您将无法向props其中传递附加值。
这是一个可能的解决方案:
// make `LeftIcon` into a function so that you
// can use it in the following way: `<LeftIcon />`
const LeftIcon = (props) => (
<div className="LeftIcon" onClick={() => {}} {...props}>
<p>I am a left icon!</p>
<p>Additional props: {JSON.stringify(props)}</p>
</div>
);
const ScreenHeader = ({ leftComponent = null }) => {
const CustomLeftComponent = leftComponent ? leftComponent : null;
const greenComponent = CustomLeftComponent
? <CustomLeftComponent style={{ color: "green" }} />
: null;
return (
<div>
<p>I am a screen header!</p>
{greenComponent}
</div>
);
};
function App() {
return (
<div className="App">
<ScreenHeader leftComponent={LeftIcon} />
<hr />
<ScreenHeader />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
或者,您可以在内部使用之前将附加信息传递props给组件:LeftIconScreenHeader
// make `LeftIcon` into a function so that you
// can use it in the following way: `<LeftIcon />`
const LeftIcon = (props) => (
<div className="LeftIcon" onClick={() => {}} {...props}>
<p>I am a left icon!</p>
<p>Additional props: {JSON.stringify(props)}</p>
</div>
);
const ScreenHeader = ({ leftComponent = null }) => {
return (
<div>
<p>I am a screen header!</p>
{leftComponent}
</div>
);
};
function App() {
return (
<div className="App">
<ScreenHeader leftComponent={<LeftIcon style={{ color: "green" }} />} />
<hr />
<ScreenHeader />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
TA贡献1851条经验 获得超3个赞
您可以使用React.cloneElement添加额外的道具
const ScreenHeader: React.FunctionComponent<ScreenHeaderProps> = ({
leftIcon = <></>,
}) => {
return (
<View>
<Header
leftComponent={React.cloneElement(leftIcon, {className: classes.myClass})}
/>
</View>
)};
添加回答
举报