2017-10-20 100 views
2

這似乎很基本,我覺得我必須誤解它是如何工作的。我有一個簡單的演示組件,它用三個ListItems呈現一個material-ui List。每個列表項目右側都有一個使用rightToggle道具實現的切換。爲了演示的目的,每個切換都以不同的方式生成。正確的Material-UI ListItem組件切換

第一個是一個基本的材料-UI切換組件。第二個是一個自定義組件包裝一個切換,第三個是通過函數調用生成的。

一些代碼:

import React from 'react'; 
import Paper from 'material-ui/Paper'; 
import { List, ListItem } from 'material-ui/List'; 
import Toggle from 'material-ui/Toggle'; 
import MyToggleComponent from './MyToggleComponent'; 


const myToggleFunction = id => <Toggle onClick={() => console.log(id)} />; 

const TestPage =() => 
    <div> 
     <Paper style={{ width: 500, padding: 15, margin: 25 }}> 
      <List> 
       <ListItem 
        primaryText="This is the first list item" 
        secondaryText="This toggle for this item is directly defined" 
        rightToggle={<Toggle onClick={() => console.log('1 - clicked')} />} 
       /> 
       <ListItem 
        primaryText="This is the second list item" 
        secondaryText="This toggle is generated from a component" 
        rightToggle={<MyToggleComponent text="2 - clicked" />} 
       /> 
       <ListItem 
        primaryText="This is the third list item" 
        secondaryText="This toggle is generated programatically" 
        rightToggle={myToggleFunction('3 - clicked')} 
       /> 
      </List> 
     </Paper> 
    </div>; 

export default TestPage; 

和自定義組件 - 非常基本的

import React from 'react'; 
import PropTypes from 'prop-types'; 
import Toggle from 'material-ui/Toggle'; 


const MyToggleComponent = ({ text }) => <Toggle onClick={() => console.log(text)} />; 

MyToggleComponent.propTypes = { 
    text: PropTypes.string.isRequired, 
}; 

export default MyToggleComponent; 

結果:

Material-UI List with misplaced Toggle

所有三種切換產生預期的控制檯輸出。第一個和第三個項目的渲染效果與我期望的在列表項右側的切換一樣。但第二個,使用自定義組件,呈現列表項上方的切換。誰能解釋爲什麼?

+0

您可以發佈截圖? –

+0

@ArslanTariq - 完成 – amay

回答

0

材料的UI是cloning引擎蓋下這些元素和被添加/注入丙風格。在第一個和第三個示例中,實際值是材料UI定義的組件,它們接受風格的屬性,如文檔here所述。然而,您自己定義的組件只傳遞文本屬性,並且不對樣式進行任何操作。因此,所有3個例子都通過了一個樣式道具,但只有第一個和第三個例子能夠做到這一點。糟糕的是沒有很好的記錄。

enter image description here

它還挺不說,它需要一個切換元件和自己的組件是不是一個,因爲它包裝的切換組件。

pushElement(children, element, baseStyles, additionalProps) { 
    if (element) { 
     const styles = Object.assign({}, baseStyles, element.props.style); 
     children.push(
     React.cloneElement(element, { // element is your own defined component 
      key: children.length, 
      style: styles, // here the style property is passed 
      ...additionalProps, // your text property is passed here 
     }) 
    ); 
    } 
} 

source

因此,要解決這個變化:

const MyToggleComponent = ({ text }) => <Toggle onClick={() => console.log(text)} />; 

到:

const MyToggleComponent = ({ text, style }) => 
<Toggle style={style} onClick={() => console.log(text)} />; 
+0

你說得對,對於不熟悉React的所有錯綜複雜的人來說,並不是立刻就顯而易見的,但這樣做的確有用。我現在可以在正確的位置切換。 – amay