2016-03-03 80 views
2

我想知道如何在使用ReactJS時在元素之間應用水平空間,當我注意到我無法解釋的差異時。React與純HTML實現之間跨度寬度的差異

下面SSCCE:(也在jsfiddle

<!doctype html> 
<html> 
    <body> 
    <span>foo</span> 
    <span style='display:inline-block; width:30px'></span> 
    <span>bar</span> 
    <div id='div0'></div> 
    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"> </script> 
    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script> 
    <script type='text/javascript'> 
    var rce = React.createElement.bind(React); 
    var x = (rce('div', {} 
     , rce('span', {}, 'foo') 
     , rce('span', {style: {display: 'inline-block', width: '30px'}}) 
     , rce('span', {}, 'bar'))); 
    ReactDOM.render(x, document.getElementById('div0')); 
    </script> 
    </body> 
</html> 

以上代碼生成的輸出:

enter image description here

鑑於DOM元素是相同的(除了的存在data-reactid屬性):

enter image description here

爲什麼然後,這種間距的差異?

回答

2

這是因爲HTML代碼在行內html元素之間的間隔。 React默認將其刪除。

<span>foo</span><span style='display:inline-block; width:30px'></span><span>bar</span> 

DEMO

同樣的結果可以用在你的HTML代碼註釋的空間來實現。

<span>foo</span><!-- 
--><span style='display:inline-block; width:30px'></span><!-- 
--><span>bar</span> 

DEMO

另外,代碼實際上確有不同。正如您可以注意到React生成的HTML中沒有空格。

enter image description here

+0

我已經接受了你的答案,但我覺得我應該刪除的問題。它不可能幫助任何其他人,因爲它根本不與React相關。 –

+0

不要刪除這個。這節省了我的一天! –