I'm using Typescript and I've got this (functional) React Native Component:
export default function BasicView(props: BasicViewProps): ReactElement {
const wRef = useRef<number>(0);
function onLayout(event: LayoutChangeEvent) {
const {width} = event.nativeEvent.layout;
wRef.current = width;
console.log('wRef: ' wRef.current);
}
return (
<View
onLayout={onLayout}
style={{
width: "100%",
justifyContent: "center",
alignItems: "center",
backgroundColor: "darkgray",
}}
>
<Text style={{ color: "white" }}>{wRef.current}</Text>
</View>
);
}
Everything seems to be working with my onLayout
code. My problem is that the content in the <Text/>
component (which is intended to be printing out wRef.current
) is not updating; currently 0
is printed and never changes. I think I partially understand why it's not updating, but my question is how do I get it to update with the value of wRef.current
?
For what it's worth, I don't plan on this component updating frequently, but I just need a single update to get the initial value of the View's layout width.
CodePudding user response:
I have tried this and it seems to be working
export default function App() {
const wRef = React.useRef(0);
const [width, setwidth] = React.useState("")
function onLayout(event: LayoutChangeEvent) {
const {width} = event.nativeEvent.layout;
wRef.current = width;
setwidth(width)
console.log('wRef: ' wRef.current);
}
return (
<View
onLayout={onLayout}
style={{
width: "100%",
justifyContent: "center",
alignItems: "center",
backgroundColor: "darkgray",
}}
>
<Text style={{ color: "white" }}>{width}</Text>
</View>
);
}
and about your issue, I have never tried printing a ref value but your problem looks like about state which is taking it's initial value, I have solved this type of issue with updating extra useState just to update state.