React Native中子组件向父组件传递Prop为null的问题排查
Hey there! Let's break down why your getThisRoute prop is showing up as null in the BusMarker component—this is a super common gotcha with class components in React, and I’ve fixed this exact issue a bunch of times.
The Root Cause
In React class components, class methods don’t automatically bind to the component’s this context. When you pass this.getRouteLine directly to your child component without binding it first, the function loses its context, which can lead to it being null or undefined when the child tries to use it.
Quick Solutions
1. Bind the Method in the Constructor
Add a constructor to your parent component and bind the getRouteLine method there. This ensures the function retains the correct this reference when passed down:
constructor(props) { super(props); this.state = { buses: [] }; // Bind the method to the component instance this.getRouteLine = this.getRouteLine.bind(this); } // Your existing getRouteLine method getRouteLine() { // Your function logic here }
2. Define the Method as an Arrow Function
Arrow functions automatically inherit the this context from their surrounding scope, so you can skip manual binding entirely. Just rewrite your method like this:
// Define using arrow function getRouteLine = () => { // Your function logic here };
Bonus: Fix Other Common Issues
While we’re at it, let’s clean up your loop code to follow React best practices:
- Always add a unique
keyprop to components created in a loop (React requires this to optimize rendering) - Use
constfor thebusvariable to avoid unintended scope issues
Here’s your updated loop code:
render() { const busMarkers = []; for(let i = 0; i < this.state.buses.length; i++){ const bus = this.state.buses[i]; // Use const instead of let busMarkers.push( <BusMarker key={bus.routeNumber} // Add unique key (use bus.id if available instead) company={bus.company} latitude={bus.location.latitude} longitude={bus.location.longitude} title={"Bus " + bus.routeNumber} description={"This bus is from " + bus.company} getThisRoute={this.getRouteLine} /> ) } return ( {/* Your parent component JSX here, including busMarkers */} ); }
Double-Check the Child Component
Make sure your BusMarker component is correctly receiving and using the prop. For example, if it’s a functional component:
const BusMarker = ({ getThisRoute, title, description, ...rest }) => { return ( <TouchableOpacity onPress={getThisRoute}> <Text>{title}</Text> <Text>{description}</Text> </TouchableOpacity> ); };
If it’s a class component, access it via this.props.getThisRoute.
内容的提问来源于stack exchange,提问作者pianoman102

