여러 인라인 스타일 개체를 결합하려면 어떻게 해야 합니까?
리액트에서는 객체를 명확하게 생성하여 인라인 스타일로 할당할 수 있습니다.아래에 기재되어 있습니다.
var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
var divStyle2 = {fontSize: '18px'};
React.render(<div style={divStyle}>Hello World!</div>, mountNode);
여러 개체를 결합하여 할당하려면 어떻게 해야 합니까?
React Native를 사용하는 경우 배열 표기법을 사용할 수 있습니다.
<View style={[styles.base, styles.background]} />
이것에 대한 자세한 블로그 투고를 확인해 주세요.
산포 연산자를 사용할 수 있습니다.
<button style={{...styles.panel.button,...styles.panel.backButton}}>Back</button
, 하다, 하다, 하다, 이렇게 할 수 요.Object.assign()
.
이 예에서는 다음 작업을 수행합니다.
ReactDOM.render(
<div style={Object.assign(divStyle, divStyle2)}>
Hello World!
</div>,
mountNode
);
그러면 두 스타일이 합쳐집니다.일치하는 속성이 있는 경우 두 번째 스타일이 첫 번째 스타일을 대체합니다.
지적한 와 같이, 은 '어느 때 보다', '어느 때 보다', ' 때 보다.Object.assign({}, divStyle, divStyle2)
하고 divStyle
.fontSize를 적용하지 않았습니다.
기본 속성을 가진 구성 요소를 만드는 데 사용합니다.를 들어.margin-right
:
const DivWithDefaults = ({ style, children, ...otherProps }) =>
<div style={Object.assign({ marginRight: "1.5em" }, style)} {...otherProps}>
{children}
</div>;
예를 들어 다음과 같이 렌더링할 수 있습니다.
<DivWithDefaults>
Some text.
</DivWithDefaults>
<DivWithDefaults className="someClass" style={{ width: "50%" }}>
Some more text.
</DivWithDefaults>
<DivWithDefaults id="someID" style={{ marginRight: "10px", height: "20px" }}>
Even more text.
</DivWithDefaults>
그 결과는 다음과 같습니다.
<div style="margin-right:1.5em;">Some text.</div>
<div style="margin-right:1.5em;width50%;" class="someClass">Some more text.</div>
<div style="margin-right:10px;height:20px;" id="someID">Even more text.</div>
리액트 네이티브와 달리 리액트에서는 스타일 배열을 통과할 수 없습니다.
<View style={[style1, style2]} />
리액트에서는 스타일 특성에 전달하기 전에 스타일의 단일 객체를 작성해야 합니다.예를 들어 다음과 같습니다.
const Header = (props) => {
let baseStyle = {
color: 'red',
}
let enhancedStyle = {
fontSize: '38px'
}
return(
<h1 style={{...baseStyle, ...enhancedStyle}}>{props.title}</h1>
);
}
ES6 스프레드 연산자를 사용하여 두 가지 스타일을 조합했습니다.Object.assign()도 같은 목적으로 사용할 수 있습니다.
이것은 스타일을 var에 저장할 필요가 없는 경우에도 사용할 수 있습니다.
<Segment style={{...segmentStyle, ...{height:'100%'}}}>
Your content
</Segment>
Object.assign()
간단한 솔루션이지만 (현재) 상위 답변이 스테이트리스 컴포넌트 작성에는 적합하지만 2개의 컴포넌트를 통합하려는 OP의 목표에는 문제가 생깁니다.state
★★★★★★★★★★★★★★★★★★.
의 인수로, 「」는 「」입니다.Object.assign()
는 실제로 첫 번째 오브젝트를 변환하여 향후 인스턴스화에 영향을 줍니다.
예:
상자에 대해 가능한 두 가지 스타일 구성을 고려합니다.
var styles = {
box: {backgroundColor: 'yellow', height: '100px', width: '200px'},
boxA: {backgroundColor: 'blue'},
};
따라서 모든 상자에 기본 '상자' 스타일을 사용하되 일부는 다른 색으로 덮어씁니다.
// this will be yellow
<div style={styles.box}></div>
// this will be blue
<div style={Object.assign(styles.box, styles.boxA)}></div>
// this SHOULD be yellow, but it's blue.
<div style={styles.box}></div>
(Once)Object.assign()
styles.styles.가 완전히됩니다.박스'를 클릭합니다.
입니다.Object.assign()
그렇게 함으로써 전달한 오브젝트로 새로운 오브젝트를 생성하도록 메서드에 지시합니다.다음과 같이 합니다.
// this will be yellow
<div style={styles.box}></div>
// this will be blue
<div style={Object.assign({}, styles.box, styles.boxA)}></div>
// a beautiful yellow
<div style={styles.box}></div>
는 React에 「Resact」를 하는 것이 합니다.Object.assign()
Redux와 같은 라이브러리를 사용하는 데 매우 유용합니다.
리액트 네이티브 스타일을 조합하는 가장 좋은 방법은 배열 주석입니다.
이것은 2개의 Style 객체를 결합하는 방법을 보여줍니다.
<Text style={[styles.base, styles.background]} >Test </Text>
Style 객체와 속성을 결합하는 방법을 보여 줍니다.
<Text style={[styles.base, {color: 'red'}]} >Test </Text>
이 기능은 모든 리액트 네이티브 애플리케이션에서 작동합니다.
const style1 = {
backgroundColor: "#2196F3",
}
const style2 = {
color: "white",
}
const someComponent = () => {
return <div style={{ ...style1, ...style2 }}>This has 2 separate styles</div>
}
이중 괄호 안에 주의해 주세요.확산 연산자는 당신의 친구입니다.
실제로 정식 결합 방법이 있으며 다음과 같습니다.
<View style={[style01, style02]} />
단, 이들 중 하나가 부모 컴포넌트에 의해 전달되고 그것이 조합된 정식 방법으로 작성되면 큰 문제가 발생합니다.
// The passing style02 from props: [parentStyle01, parentStyle02]
// Now:
<View style={[style01, [parentStyle01, parentStyle02]]} />
이 마지막 줄에서는 UI 버그가 발생합니다.즉, React Native는 어레이 내의 깊은 어레이를 처리할 수 없습니다.그래서 도우미 기능을 만듭니다.
import { StyleSheet } from 'react-native';
const styleJoiner = (...arg) => StyleSheet.flatten(arg);
my anywhere를 사용하면 어떤 스타일과 스타일을 조합할 수 있습니다.심지어.undefined
다른 쓸모없는 타입은 스타일을 망치지 않습니다.
다음과 같이 클래스를 인라인 스타일링과 결합할 수도 있습니다.
<View style={[className, {paddingTop: 25}]}>
<Text>Some Text</Text>
</View>
개체의 속성을 병합해야 합니다.예를들면,
const boxStyle = {
width : "50px",
height : "50px"
};
const redBackground = {
...boxStyle,
background: "red",
};
const blueBackground = {
...boxStyle,
background: "blue",
}
<div style={redBackground}></div>
<div style={blueBackground}></div>
나는 이것이 나에게 가장 잘 맞는다는 것을 알았다.예상대로 오버라이드 됩니다.
return <View style={{...styles.local, ...styles.fromProps}} />
컴포넌트를 사용할 수 있습니다.
const styles = StyleSheet.create({
divStyle :{
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
},
divStyle2 :{fontSize: '18px'}
})
React.render(<div style={StyleSheet.compose(styles.divStyle, styles.divStyle2)}>Hello World!</div>, mountNode);
또는
React.render(<div style={[styles.divStyle, styles.divStyle2]}>Hello World!</div>, mountNode);
리액트에서 이 솔루션을 찾는 경우 내부 스타일에서 스프레드 연산자를 사용하려면 babel-plugin-transform-object-rest-spread를 사용해야 합니다.
npm 모듈에서 설치하고 다음과 같이 .babelrc를 설정합니다.
{
"presets": ["env", "react"],
"plugins": ["transform-object-rest-spread"]
}
그럼 이렇게...
const sizing = { width: 200, height: 200 }
<div
className="dragon-avatar-image-background"
style={{ backgroundColor: blue, ...sizing }}
/>
상세정보 : https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/
반응 js에 여러 스타일을 인라인으로 추가하려면 다음과 같이 할 수 있습니다.
<div style={{...styles.cardBody,...{flex:2}}}>
그래서 기본적으로 저는 이것을 잘못된 시각으로 보고 있습니다.내가 보기에 이것은 리액트 고유의 질문이 아니라 두 개의 JavaScript 개체를 결합하는 방법에 대한 JavaScript 질문입니다(비슷한 이름의 속성을 클로버링하지 않고).
이 StackOverflow 답변에서는 이에 대해 설명합니다.두 JavaScript 개체의 속성을 동적으로 병합하려면 어떻게 해야 합니까?
jQuery에서는 확장 메서드를 사용할 수 있습니다.
@PythonIsGreat가 말한 내용을 확장하기 위해, 나는 나를 위해 그것을 할 수 있는 글로벌 함수를 만듭니다.
var css = function(){
var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0));
return $.extend.apply(null, args);
}
이렇게 하면 객체가 새 객체로 깊이 확장되고 다양한 수의 객체를 매개 변수로 사용할 수 있습니다.이를 통해 다음과 같은 작업을 수행할 수 있습니다.
return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);
var styles = {
base:{
//whatever
},
first:{
//whatever
},
second:{
//whatever
}
}
이 기능을 한층 더 진행하려면 , 클래스명과 같은 도우미 기능을 작성할 수 있습니다.
const styleRules = (...rules) => {
return rules.filter(Boolean).reduce((result, rule) => {
return { ...result, ...rule };
}, {});
};
그런 다음 컴포넌트에서 조건부로 사용합니다.
<div style={
styleRules(
divStyle,
(window.innerWidth >= 768) && divStyleMd,
(window.innerWidth < 768) && divStyleSm
)
}>Hello World!</div>
인라인 스타일링 방법:
<View style={[styles.red, {fontSize: 25}]}>
<Text>Hello World</Text>
</View>
<View style={[styles.red, styles.blue]}>
<Text>Hello World</Text>
</View>
<View style={{fontSize:10,marginTop:10}}>
<Text>Hello World</Text>
</View>
다음과 같은 조건에 따라 스타일을 추가하려면 이 모듈을 작성했습니다.
multipleStyles(styles.icon, { [styles.iconRed]: true })
https://www.npmjs.com/package/react-native-multiple-styles
React에 여러 인라인 스타일이 있는 경우.
<div onClick={eleTemplate} style={{'width': '50%', textAlign: 'center'}}/>
언급URL : https://stackoverflow.com/questions/29979324/how-to-combine-multiple-inline-style-objects
'programing' 카테고리의 다른 글
스프링 부트 javax.validation을 올바르게 주입하는 방법검증자 (0) | 2023.02.23 |
---|---|
JsonParser는 더 이상 사용되지 않습니다. (0) | 2023.02.23 |
Jackson JSON Marshall은 getter를 무시합니다. (0) | 2023.02.23 |
Angular Http - 약속 또는 구독 (0) | 2023.02.23 |
$window 또는 $location을 사용한 각도 리다이렉트JS (0) | 2023.02.23 |