Reactjs 如何更改React.Node';s道具基于另一道具
我正在使用Reactjs 如何更改React.Node';s道具基于另一道具,reactjs,react-proptypes,Reactjs,React Proptypes,我正在使用道具类型检查类型并将默认设置为我的组件道具。我的一个道具是显示SVG图像的React.Node的颜色 Rating.defaultProps = { iconColor: '#E5C100', iconFull: <StarSharp /> iconEmpty: <StarBorderSharp /> iconHalfFull: <StarHalfSharp /> } Rating.propTypes = { iconColor:
道具类型
检查类型并将默认设置为我的组件道具。我的一个道具是显示SVG图像的React.Node的颜色
Rating.defaultProps = {
iconColor: '#E5C100',
iconFull: <StarSharp />
iconEmpty: <StarBorderSharp />
iconHalfFull: <StarHalfSharp />
}
Rating.propTypes = {
iconColor: Proptypes.string,
iconFull: Proptypes.Node,
iconEmpty: Proptypes.Node,
iconHalfFull: Proptypes.Node
};
Rating.defaultProps={
iconColor:“#E5C100”,
iconFull:
我的敌人:
Iconhalfull:
}
Rating.propTypes={
iconColor:Proptypes.string,
iconFull:Proptypes.Node,
iconEmpty:Proptypes.Node,
IconHalfull:Proptypes.Node
};
我想在我的渲染方法中以
style={color:this.props.iconColor}
的形式传递iconColor
,但我不确定如何传递。我试图寻找答案,但似乎找不到答案 如果我正确理解了您的问题,那么您应该能够通过首先检查组件的props
中的有效iconColor
来计算样式,然后返回到Rating.defaultProps
提供的默认iconColor
属性(如果需要)
为了说明这一技术,请考虑以下内容:
class Rating extends React.Component {
render() {
// If iconColor is undefined/falsey in this components props, then
// fallback to the default iconColor prop as specified in the
// Rating.defaultProps object
const style = {
color : (this.props.iconColor || Rating.defaultProps.iconColor)
};
// Return your JSX as needed, with locally computed style object
return (<div style={ style }>
...
</div>)
}
}
Rating.defaultProps = {
iconColor: '#E5C100',
iconFull: <StarSharp />
iconEmpty: <StarBorderSharp />
iconHalfFull: <StarHalfSharp />
}
Rating.propTypes = {
iconColor: Proptypes.string,
iconFull: Proptypes.Node,
iconEmpty: Proptypes.Node,
iconHalfFull: Proptypes.Node
};
等级扩展了React.Component{
render(){
//如果此组件道具中的iconColor未定义/错误,则
//退回到中指定的默认iconColor属性
//Rating.defaultProps对象
常量样式={
颜色:(this.props.iconColor | | Rating.defaultProps.iconColor)
};
//根据需要使用本地计算的样式对象返回JSX
返回(
...
)
}
}
Rating.defaultProps={
iconColor:“#E5C100”,
iconFull:
我的敌人:
Iconhalfull:
}
Rating.propTypes={
iconColor:Proptypes.string,
iconFull:Proptypes.Node,
iconEmpty:Proptypes.Node,
IconHalfull:Proptypes.Node
};
我找到了一种不依赖CSS继承的方法:
const iconFull = React.cloneElement(props.iconFull, {'style': props.iconStyles});
const iconEmpty = React.cloneElement(props.iconEmpty, {'style': props.iconStyles});
const iconHalfFull = React.cloneElement(props.iconHalfFull, {'style': props.iconStyles});
我将道具从
iconColor
(字符串)更改为iconStyles
(对象),以使其成为更广泛的功能您可以为当前的渲染方法实现(或只是相关部分)包含代码吗?这是唯一相关部分您确实正确理解问题,并且解决方案在这种情况下确实有效。我知道有一种方法可以在React.节点位于变量内部时直接更新它们,而不是依赖CSS继承。