首页 > 解决方案 > 基于 Rect 中的 prop 渲染内联样式

问题描述

我正在为 texfield 构建一个可重用的组件,该组件根据位置使用两种不同的内联样式

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

我讨厌每次使用该组件时都必须指定这一点。本质上,我希望第二个样式被默认,而第一个样式由 boolean prop 访问,例如 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}/> 

先感谢您

标签: reactjs

解决方案


为什么你不能这样尝试

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}/> 

推荐阅读