2017-05-29 62 views
0

我想用一些ReactJS初始化Reactjs成分與屬性

致以傳統的HTML應用程序

我可以簡化爲:

<body> 
    <my-component property="abc" /> 
    <my-component property="123" /> 
</body> 

我如何可以訪問內部React.Component的property價值?

+4

'this.props.property' ...查看介紹的反應文檔:https://facebook.github.io/react/docs/components-and-props.html。 –

+0

我的大部分HTML都在後端服務器上呈現,我想用React組件創建更多的互動功能。我遇到的問題是如何將數據從靜態HTML傳遞到React組件。與主幹我會使用data- *屬性,但我不知道如何訪問它(容器元素上的數據) – Fuxi

回答

0

我不知道我是否理解你的問題,但如果你想要的是擴展一些HTML組件,你應該使用傳播屬性。 https://facebook.github.io/react/docs/jsx-in-depth.html#spread-attributes

自定義圖像:

import React from 'react'; 
import ReactDOM from 'react-dom'; 

const MyImage = (props) => { 
    // get your customized atribute 
    const {log, alt, ...properties} = props; 

    // Do wherever you want 
    console.log(log); 

    // Pass the rest to the image 
    return <img alt={alt} {...properties}/>; 
}; 

ReactDOM.render(
    <MyImage log="logging action" 
     alt="React logo" 
     style={{ width: "400px", height: "400px"}} 
     src="https://cdn.worldvectorlogo.com/logos/react.svg" />, 
    document.getElementById('root') 
); 

注意:要理解爲什麼alt屬性附加傷害不獲通過與其他屬性訪問此鏈接https://github.com/evcohen/eslint-plugin-jsx-a11y/issues/7

+0

我的大部分HTML在後端服務器上呈現,我想用React創建更多的交互功能組件。我遇到的問題是如何將數據從靜態HTML傳遞到React組件。與主幹我會使用data- *屬性,但我不知道如何訪問它(容器元素上的數據) – Fuxi