2017-10-20 63 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