我是新來的反應。我有 a 的寬度和高度,<View>我想將這些資料傳遞給<Child>包含這兩個道具的組件。我已經<View>在寬度和高度上破壞了布局,但似乎我無法將這些變數傳遞給<Child>(未定義的名稱)。
這是代碼:
<View onLayout={(event) => { let { width, height } = event.nativeEvent.layout;}} >
<Child width={width} height={height } />
</View>
謝謝
uj5u.com熱心網友回復:
使用 useState 鉤子的替代解決方案:
export default function App() {
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
return (
<View onLayout={(event) => {
let { width, height } = event.nativeEvent.layout
setWidth(width); setHeight(height);
}}>
<Child width={width} height={height} />
</View>
);
}
uj5u.com熱心網友回復:
如果你注意你的代碼,你會看到,width而height不是在范圍之內。它們存在于您的事件處理程式的范圍內。因此,您將不存在的變數傳遞給孩子。
此外,正確的方法是使用狀態。例如,如果您的視圖是在名為AppViewthen的類中創建的
class AppView extends React.Component {
constructor(props) {
super(props)
this.state = {
width: null,
height: null,
}
}
render() {
return (
<View onLayout={(event) => {
let { width, height } = event.nativeEvent.layout
this.setState({width: width, height: height}
}}>
<Child width={this.state.width} height={this.state.height} />
</View>
)
}
}
這樣每次onLayout觸發事件時,它都會設定狀態變數width和height。然后將修改后的值傳遞給子元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368749.html
