Есть несколько способов, которыми вы можете go об этом, вот примеры того, как вы можете реализовать это, в итоге, реализация здесь использует объект как Ha sh, чтобы возвратить значение га * 1019. * используя тип в качестве ключа.
class Circle { // extends React.Component.
constructor(props = {}) {
this.props = props;
}
render() {
let circleStyle = {
position: "relative",
left: "50%",
top: "45%",
transform: "translate(-50%, 0)",
//I need this to change according to this.props.type
//I'd put a switch in here if I could
borderColor: this.borderColor[ this.props.type ] || 'default',
borderStyle: "solid",
borderWidth: "0.5vh",
borderRadius: "50%",
width: "20vh",
height: "20vh",
}
console.log( circleStyle.borderColor );
}
get borderColor() {
return {
'type_a': 'red',
'type_b': 'blue',
'type_c': 'green',
}
}
}
// default value
const circle_1 = new Circle({});
circle_1.render();
// red
const circle_2 = new Circle({ type: 'type_a' });
circle_2.render();
// blue
const circle_3 = new Circle({ type: 'type_b' });
circle_3.render();
// green
const circle_4 = new Circle({ type: 'type_c' });
circle_4.render();
В приведенном выше примере, если тип не определен, вместо него будет использоваться значение по умолчанию.
На основании вашего исходного примера кажется, что вы используете React. Я бы посоветовал извлечь стили в отдельную функцию, чтобы ваш метод render()
стал немного более чистым, в том числе благодаря тому, что вы могли бы протестировать эту часть изолированно.
const BORDR_TYPES = {
'type_a': 'red',
'type_b': 'blue',
'type_c': 'green',
};
// this one extracts the type property from the properties object when generateStyles is called
// and initialize the default value to empty object when no value is passed to this function.
const generateStyles = ( { type, ...props } = {} ) => ({
position: "relative",
left: "50%",
top: "45%",
transform: "translate(-50%, 0)",
//I need this to change according to this.props.type
//I'd put a switch in here if I could
borderColor: BORDR_TYPES[ type ] || 'default',
borderStyle: "solid",
borderWidth: "0.5vh",
borderRadius: "50%",
width: "20vh",
height: "20vh",
})
console.log( generateStyles().borderColor );
console.log( generateStyles({ type: 'type_a' }).borderColor );
console.log( generateStyles({ type: 'type_b' }).borderColor );
console.log( generateStyles({ type: 'type_c'}).borderColor );
class Circle { // extends React.Component.
constructor(props = {}) {
this.props = props;
}
render() {
const circleStyle = generateStyles( this.props );
console.log( circleStyle.borderColor );
}
}