tin*_*ker 2 javascript reactjs
我正在创建一个 React 应用程序,我有一个如下所示的代码段:
import React, { Component } from 'react';
import { RaisedButton } from 'material-ui';
let isZero = false;
class Button extends Component {
render() {
const { value } = this.props;
isZero = false;
if (value === 0) {
isZero = true;
}
// removed for brevity
}
}
const styles = {
otherStyles: {
minWidth: isZero ? '120px' : '60px',
margin: '5px 5px 5px 0',
lineHeight: isZero ? '120px' : '60px',
},
};
export default Button;
Run Code Online (Sandbox Code Playgroud)
但是,显然条件语句不适用于对象内部,因为当value为 0 时,我仍然得到了60px而不是120px. 有任何想法吗?
您的样式是在渲染之外定义的,因此不会在每次变量 isZero 更改时计算,如果您希望它是动态的,请在渲染中定义它
import React, { Component } from 'react';
import { RaisedButton } from 'material-ui';
class KeyPadButton extends Component {
isZero = false;
render() {
const { click, disabled, value } = this.props;
this.isZero = false;
if (value === 0) {
this.isZero = true;
console.log(value);
console.log(isZero);
console.log(styles.buttonStyles);
console.log(styles.otherStyles);
}
const styles = {
buttonStyles: {
float: 'left',
width: this.isZero ? '120px' : '60px',
height: this.isZero ? '120px' : '60px',
border: '1px solid #f9f9f9',
borderRadius: '5px',
},
otherStyles: {
minWidth: this.isZero ? '120px' : '60px',
margin: '5px 5px 5px 0',
lineHeight: this.isZero ? '120px' : '60px',
},
};
return (
<RaisedButton label={value}
buttonStyle={styles.buttonStyles}
style={styles.otherStyles}
disabled={disabled}
onClick={() => click(value)}
/>
);
}
}
export default KeyPadButton;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12806 次 |
| 最近记录: |