reactjs - 基于 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}/>
先感谢您
解决方案
为什么你不能这样尝试
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}/>
推荐阅读
- python - 有没有办法在 Pytorch 中使用 2d 张量作为 MLP 的输入?
- haskell - 使用 Foldmap 的 Haskell 平均函数
- jquery - 刷新网页后停用鼠标移动事件不起作用
- javascript - 使用对象而不是布尔更改应用程序流
- python-3.x - 使用 Visual Studio 代码 Python 3.8.5 打印时出现语法错误
- python - 从用户获取日期输入并使用python作为参数传递
- xamarin - System.NotSupportedException:'无法从本机句柄激活 SkiaSharp.Views.Forms.SKCanvasViewRenderer 类型的实例'
- scala - 一个动作返回 Future[Result] 而其他返回 Accumultor[]
- typescript - 当我们在vs代码工作区中保存文件时如何获取新修改行的行号?
- c# - 在 .Net Standard 2.0 中替换 string.Contains(string, StringComparison)