我想使用 React v16.0.0 的新功能来返回一个字符串,然后在中使用该字符串
<img src="returnedString" >
当前的行为是什么?
好吧,如果我在一个
<div > <MyComponent /> </div>
我可以看到屏幕上显示的字符串(见附带的屏幕截图),但我的目标是在 <img src="returnedString" />
中使用该字符串
这是我的代码:
// My component that returns strings
class MyComponent extends Component {
render(){
switch (this.props.type) {
case 'text':
return this.props.json.data[this.props.Key]
break
case 'image':
return this.props.json.data[this.props.Key]
break
default:
return null
break
}
}
}
const UserComponent = (props) => {
return (
<div>
{/* this displays the string on the page */}
<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />
{/* If I console.log this line I get <img src={[object object]} /> */}
<img src={<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />} />
</div>
)
}
// Parent Component
class App extends Component {
constructor(props){
super(props)
this.state = {
json:[]
}
}
// Fetching data from an api
componentDidMount(){
fetch("https://reqres.in/api/users/2")
.then(response => response.json())
.then(json => {
this.setState({json: json })
})
}
render() {
return (
<div>
<UserComponent {...this.state}/>
</div>
);
}
}
export default App;
我怎样才能做到这一点?
预期的行为是什么?
我想在
中使用返回的字符串React 有哪些版本?
react v16.0.0
这在以前版本的 React 中有效吗?
不,因为它是 React v16.0.0 中的新功能
最佳答案
如果您想动态设置图像的 src
属性,请使用普通的 javascript 函数而不是组件:
const getImageSrc = props => {
switch (props.type) {
case 'text':
case 'image':
return props.json.data[props.Key]
}
}
然后您可以从组件的 render
方法中调用它,如下所示:
<img src={ getImageSrc({...this.props, type: 'image', Key: 'avatar'}) } />
关于javascript - 如何在图像 ex : <img src ='returnedString' />? 的源标记中使用返回的字符串(React v16.0.0 的新功能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46438737/