在React中,你可以清楚地创建一个对象,并将其赋值为内联样式。即. .下面所提到的。
var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
var divStyle2 = {fontSize: '18px'};
React.render(<div style={divStyle}>Hello World!</div>, mountNode);
如何组合多个对象并将它们分配在一起?
其实有一种正式的组合方式,如下所示:
<View style={[style01, style02]} />
但是,有一个小问题,如果其中一个被父组件传递,并且它是通过组合形式的方式创建的,我们就有一个大问题:
// The passing style02 from props: [parentStyle01, parentStyle02]
// Now:
<View style={[style01, [parentStyle01, parentStyle02]]} />
最后一行导致UI bug, React Native不能处理数组中的深数组。所以我创建了我的helper函数:
import { StyleSheet } from 'react-native';
const styleJoiner = (...arg) => StyleSheet.flatten(arg);
通过使用我的styleJoiner,你可以在任何地方组合任何类型的风格和组合风格。即使是未定义的或其他无用的类型也不会破坏样式。