react-native 默认不能支持 checkbox,内置的 CheckBox 组件只能在安卓下工作。看了一堆第三方组件,都需要借助 Image 或 Icon 来实现。在 stackoverflow 看到一个帖子之后,觉得用 View 来实现最简单,而且不需要加载额外任何资源。
import { View } from 'react-native'
import { PureComponent } from 'react'
export class CheckboxButton extends PureComponent {
render() {
const { color = '#333333', checked, onChange, style = {} } = this.props
return (
<View style={{
height: 24,
width: 24,
borderWidth: 2,
borderColor: color,
alignItems: 'center',
justifyContent: 'center',
...style,
}} onResponderRelease={onChange}>
{
checked ? <View style={{
height: 12,
width: 12,
backgroundColor: color,
}}/> : null
}
</View>
)
}
}
export default CheckboxButton
这个道理和通过 div 来画一个三角形一样,也是通过边框、背景组合得到。基于这种方法 RadioButton 就是增加一个 borderRadius,也是非常容易。

