javascript - 如何在图像 ex : <img src ='returnedString' />? 的源标记中使用返回的字符串(React v16.0.0 的新功能)

标签 javascript reactjs react-fiber

我想使用 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 中的新功能

enter image description here

最佳答案

如果您想动态设置图像的 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/

相关文章:

javascript - React.Component 'this' 在 ComponentDidMount 中更改

javascript - 如何找到元素的x中心坐标和相关的窗口偏移量

javascript - 消息 : Object doesn't support this property or method

javascript - Javascript 中的 PHP 数组?

javascript - 在 prop set 上的高阶组件内执行逻辑运算

reactjs - 如何确保 Next.js router.query 不是未定义的?

reactjs - React 与 React Fiber 有什么区别?

javascript - 虚拟 DOM 到底存储在哪里?

javascript - 在今天改变 UL 背景

reactjs - 未捕获的 TypeError : _materialUi. Styles.ThemeManager 不是函数