需求。本书接上文,这里对UI积累的select部分多了两个要求。当我点击选择一个选项时,我应该看到的是我选择的选项的内容在多个实例中被复用了,也就是说,它也是一个选择,我只需要改变一些东西,其余的保持不变,这样作为选区中的文字内容,font-size,font-family,选区宽度,高度等。.只开发一个组件,如何满足这种“不合理的要求”?第一虎——显示选项内容我们的dom是这样的:Pleaseselectoneoption...具体实现可以通过react的状态轻松实现。将onChange事件绑定到select并触发onSelect方法。Whentheoptionoftheselectisselected,theselectedvalueispassedtothespanthatisactuallydisplayed.问题是:1)如何得到它。2)如何给1)如何获取:点击时,通过event.target.value获取选中选项的值2)如何给:组件渲染时,构造函数中的state定义一个值来存储选中的值,调用showValue,选中的时候,在onSelect方法中,获取到event.target.value后,设置为这个值,同时dom中的span绑定this.state.showValue的值.话不多说,看代码完整代码如下:){这个.setState({showValue:e.target.value});}render(){return(<选项>...选项>{this.state.showValue});}}示例图:二虎——组件化从上面的代码可以看出,引入这个选区的方式是render()但是你的选区,我要在同一个页面引入N个,其中一个高度应该是40px,另一个宽度要长一些,500px,另一个的长宽不用改。你可以帮我改变这个选择的默认词,它不叫Pleaseselectoneoption...,whatisitcalled嗯,请选择一个选项...,还有一个,你保持原样,谢谢WTF,怎么办?求,没办法。为了方便开发,我自己设计的。如果可以组件化,在引入的时候可以选择性的定义几个属性。例如:render(
)这太完美了。怎么做呢,这个就是引入一个叫prop-types的包,定义属于这个组件的变量,然后应用到组件各个dom的css上。下面以上面为例。定义属于这个组件的类型:Selection.propTypes={height:PropTypes.oneOfType([PropTypes.number,PropTypes.string,]),width:PropTypes.oneOfType([PropTypes.number,PropTypes.string,]),words:PropTypes.string}Selection.defaultProps={height:'30px',width:'300px',words:'Pleaseselectoneoption...'}然后就是通过react的this.props引入啦Talkischeap,showmethecodeindex.jsclassAppextendsComponent{render(){return(
);}}Selection.jsclassSelectionextendsComponent{constructor(props){super(props)this.state={showValue:this.props.words}}onSelect(e){this.setState({showValue:e.target.value});console.log(e.target.value)}render(){const{width,height}=this.propsconststyle={width:width,height:height}constsuitableHeight=(parseInt(height.substring(0,height.length-2))-30)/2+6;constspanStyle={width:width,height:height,paddingTop:suitableHeight}constarrowStyle={top:suitableHeight}return(
{this.state.showValue}</div>);}}Selection.propTypes={height:PropTypes.oneOfType([PropTypes.number,PropTypes.string,]),width:PropTypes.oneOfType([PropTypes.number,PropTypes.string,]),words:PropTypes.string}Selection.defaultProps={height:'30px',width:'300px',words:'请选择一个选项...'}效果图:嗯。.应该差不多吧。这里的代码忽略了使用自定义属性时对纯数字和字符串的判断。当高度小于30时,进行判断处理。有兴趣的,自己加ok,收工。