我是本機反應的新手。所以我有這個組件:它將從父組件獲取一個 prop x。是否可以根據 x僅更改黃色視圖的背景顏色?或者我應該單獨渲染視圖而不是使用地圖?任何幫助將不勝感激
const [colors, setColors] = useState(["yellow", "blue", "green", "red"]);
return ( <View style={{
width: "100%",
height: "100%",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
flexWrap: "wrap",}}>
{colors.map((color, index) => (
<View
key={index}
style={{height: "25%",backgroundColor:color,}}></View>))}
</View>);};```
uj5u.com熱心網友回復:
backgroundColor: color === 'yellow' ? (xCondition ? randomColor : color) : color
不建議嵌套三元運算,因此更好的方法是使用一個回傳顏色的函式,如:
function getColor(x, currentColor){
if(currentColor === 'yellow') {
return xCondition ? randomColor : currentColor
}
return currentColor
}
和
backgroundColor: getColor(x, currentColor)
uj5u.com熱心網友回復:
首先,當你return在 .
import { Fragment, useMemo } from 'react'
const [colors, setColors] = useState(["yellow", "blue", "green", "red"]);
const getColors = useMemo(()=>{ <Fragment> {colors.map ... } </Fragment> } , [colors, props.x])
return (
<View style={{
width: "100%",
height: "100%",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
flexWrap: "wrap",}}>
{getColors}
現在,只有colors任一處的變化props.x才會使這件作品運行,并且在其中,我們可以memo用來保證僅yellow會發生變化
import {memo} from 'react'
const MappedColor = memo(props =>
<View
key={props.index}
style={{height: "25%",backgroundColor:props.color,}}></View>))}
</View>,
(props, nextProps) => nextProps.color != 'yellow' || props.x == nextProps.x)
colors.map((color,idx) => <MappedColor color={color} key={idx} x={props.x}/>)
uj5u.com熱心網友回復:
嗨,這段代碼有問題,您必須在地圖中為父級或視圖提供寬度和高度,您必須查看您想要做什么
{colors.map((color, index) => (
<View
key={index}
style={{ height: 50 , backgroundColor: color , width: 50 }}
></View>
))}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/353520.html
標籤:反应原生
