簡體   English   中英

如何在圖像的源標簽中使用返回的字符串(React v16.0.0 的新特性):<img src='returnedString' /> ?

[英]How Can I use the returned string (new feature of React v16.0.0) in the source tag of an image ex: <img src='returnedString' />?

我想使用 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 ?

反應 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'}) } />

因為這

<MyComponent type='image' Key='avatar' desc='Abified image' />

正在 dom 中創建一個文本節點

但在這種情況下

<img src={<MyComponent type='image' Key='avatar' desc='Abified image' {...props} />

您的 src 屬性正在獲取一個react 元素對象

你永遠不會得到這樣的字符串。 如果您想動態獲取src ,請嘗試這樣的操作

const UserComponent = (props) => {
// calculate you src here
 const imageSrc = props.json.data['avatar'];
 return (
   <div> 
     <img src={ imageSrc } />
   </div> 
 )
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM