这看起来很基本,我觉得我必须误解它是如何运作的。我有一个简单的演示组件,它使用三个ListItem呈现一个material-ui List。每个列表项在右侧都有一个使用rightToggle prop实现的切换。出于演示的目的,每个切换的生成方式都不同。
第一个是基本材质-ui Toggle组件。第二个是包装Toggle的自定义组件,第三个是由函数调用生成的。
一些代码:
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;
结果:
所有三个切换都会生成预期的控制台输出。第一个和第三个项目正如我所期望的那样呈现在列表项右侧的Toggle。但是第二个,使用自定义组件,在列表项上方呈现切换。任何人都可以解释原因吗?
答案 0 :(得分:0)
Material-UI是cloning这些元素,并且正在添加/注入道具样式。在第一个和第三个示例中,实际值是Material UI定义的组件,它们接受标记为here的属性样式。但是,您自己定义的组件只传递text属性,并且不对样式执行任何操作。
所以归结为所有3个例子都通过了样式道具,但只有第一个和第三个例子用它做了一些事情。对于坏事,这没有很好的记录。
有点确实说它需要是一个Toggle元素而你自己的组件不是一个,因为它包装了Toggle组件。
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
})
);
}
}
所以要解决这个改变:
const MyToggleComponent = ({ text }) => <Toggle onClick={() => console.log(text)} />;
为:
const MyToggleComponent = ({ text, style }) =>
<Toggle style={style} onClick={() => console.log(text)} />;