代码之家  ›  专栏  ›  技术社区  ›  LOTUSMS

基于prop-in-Rect绘制内联样式

  •  1
  • LOTUSMS  · 技术社区  · 7 年前

    style={{marginTop:15, marginBottom:35}} // the first of type needs a top margin
    style={{marginTop:0, marginBottom:35}} // all others 
    

    我讨厌每次使用组件时都要指定这个。基本上,我希望第二种样式是默认的,第一种样式是由一个布尔属性访问的,比如firstOfType={true}……这将使firstOfType={false}成为默认样式,这样我甚至不必在视图中指定它。

    这就是我的组件的样子

    import React from 'react';
    import PropTypes from 'prop-types';
    import TextField from 'material-ui-next/TextField';
    
    const CMInputField = ({label, value, onChange, rows, margin, style}, context) => {
        return (
            <TextField
                label={context.t(label)}
                value={value}
                onChange={onChange}
                InputLabelProps={{shrink: true}}
                style={{marginTop:0, marginBottom:35}} //the defaulted one
                fullWidth
                multiline
                rows={rows}
                margin={margin}/> 
        );
    };
    
    CMInputField.defaultProps = {
        margin: 'normal',
        fullwidth: true,
        multiline: false,
        firstOfType: false,
    };
    
    CMInputField.propTypes = {
        label: PropTypes.string,
        value: PropTypes.object,
        onChange: PropTypes.func,
        style: PropTypes.object,
        fullwidth: PropTypes.bool,
        multiline: PropTypes.bool,
        rows: PropTypes.string,
        margin: PropTypes.string,
        firstOfType: PropTypes.bool,
    };
    
    CMInputField.contextTypes = {
        t: PropTypes.func.isRequired,
    };
    
    export default CMInputField;
    

    我会这样说:

    <CMInputField
        label="First Input"
        value="Hello"
        onChange={this.myFunction}
        firstOfType/> 
    
    <CMInputField
        label="Second Input"
        value="Hello Again"
        onChange={this.myFunction2}/> 
    

    先谢谢你

    1 回复  |  直到 7 年前
        1
  •  2
  •   halfer Jatin Pandey    7 年前

    你为什么不能这样试

    const CMInputField = ({label, value, onChange, rows, margin, style}, context) => {
        let textFieldStyle = {"marginTop":0, "marginBottom":35};
        if(firstOfType) textFieldStyle= {"marginTop":15, "marginBottom":35};
        return (
            <TextField
                label={context.t(label)}
                value={value}
                onChange={onChange}
                InputLabelProps={{shrink: true}}
                style={textFieldStyle} //the defaulted one
                fullWidth
                multiline
                rows={rows}
                margin={margin}/> 
        );
    };
    
    <CMInputField
        label="First Input"
        value="Hello"
        onChange={this.myFunction}
        firstOfType={true}/> 
    
    <CMInputField
        label="Second Input"
        value="Hello Again"
        onChange={this.myFunction2}
        firstOfType={false}/>