当我渲染一个组件时,它的 props
显示它具有正确的值,但是它生成的 div 元素丢失了 background-position-x
或 背景位置-y
。
我在父类中做了类似下面的事情:
//Class ImageSelector is roughly:
onClick() {
this.state.image = randomlySelectImage()
}
render() {
return <ItemIcon image={this.state.image}/>
}
有问题的图标:
class Icon extends React.component
render() {
console.log(this.props.image)
let style = {
width: 48,
height: 48,
background: `url('./img/${this.props.image.sprite}')`,
backgroundPositionX: -this.props.image.x,
backgroundPositionY: -this.props.image.y
}
return <div style={style}/>;
}
当错误发生时,React 开发工具显示 Icon 确实有适当的可用值 x = 192
和 y = 384
,甚至 div 的 style
显示正确的值,而检查时的 div 元素如下所示:url("./img/sprite0.png") -384px
。 x
值丢失,我不明白为什么。
最佳答案
虽然最初的问题似乎没有解决方案(至少从 React v15.3.2 开始),解决方法最终是指定 backgroundPositionX
和 backgroundPositionY
作为一部分background
属性。
class Icon extends React.component
render() {
let style = {
width: 48,
height: 48,
background: `url('./img/${this.props.image.sprite}') ${-this.props.image.x}px ${-this.props.image.y}px`
}
return <div style={style}/>;
}
关于javascript - 有时未设置内联样式的 background-position-x 或 y 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40342949/