Estoy un poco perdido cuando se trata de pasar un estado de un componente a una función. Pasé con éxito un estado de Inicio a ListHome (un componente que se importa y se procesa en Inicio), pero tengo dificultades para continuar pasándolo a una función que se está procesando en ListHome (Slider). Principalmente debido a que es una función.
Revisé los documentos nuevamente, pero todavía estoy luchando por entender cómo debería funcionar esto. ¡Una edición/ejemplo directo sería muy útil!
Estoy renderizando Home en una pila en App.js. Si desea que incluya este archivo, hágamelo saber.
Aprecio cualquier idea en absoluto más de lo que sabes.
Inicio.js
export default class Home extends React.Component { constructor(props) { super(props) this.state ={ visible: true, whichComponentToShow: 'Screen1' }; } goToMap = () => { this.setState({whichComponentToShow: 'Screen2'}) } goToList = () => { this.setState({whichComponentToShow: 'Screen1'}) } render(){ if(this.state.whichComponentToShow === 'Screen1'){ return( <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}> <ListHome renderMap = {this.goToMap.bind(this)} renderList = {this.goToList.bind(this)} />ListHome.js
export default class ListHome extends React.Component { goToMap = () => { this.props.renderMap(); } goToList = () => { this.props.renderList(); } render() { return ( <Slider renderMap = {this.goToMap.bind(this)} renderList = {this.goToList.bind(this)} />Slider.js (no he implementado nada en este archivo en un intento de pasar el estado todavía)
const Slider = (props) => { const [active, setActive] = useState(false) let transformX = useRef(new Animated.Value(0)).current; //animation code I removed that uses the above const and let return ( //code I removed that just creates a button. //The touchable opacity is how I want to use the state. <TouchableOpacity onPress={() => this.goToMap}> </TouchableOpacity> ); } export default SliderSus devoluciones de llamada de estado y configuración de estado se definen como métodos de clase en el componente de clase Home . Puede acceder a ellos con this.goToMap y this.goToList y pasarlos a ListHome como accesorios de componentes.
En el componente de clase ListHome , puede acceder a cada uno con this.props.renderMap y this.props.renderList porque así se nombran los accesorios.
En el componente de la función Slider , puede acceder a cada uno con props.renderMap y props.renderList porque así se nombran los accesorios (tenga en cuenta la falta de this para acceder a los accesorios en un componente de función).
Esto se conoce comúnmente como perforación puntal. Simplemente está pasando una referencia a la función original desde App -> ListHome -> Slider para que eventualmente pueda ejecutarse.
No hay necesidad de volver a definir esta función en el camino hacia abajo. Todo lo que dice es que cuando hay un evento onPress/onClick , ejecute la función. Y la función que quieres ejecutar es la definida en Home .
import "./styles.css"; import React from "react"; export default class Home extends React.Component { constructor(props) { super(props); this.state = { whichComponentToShow: "Screen1" }; } goToMap = () => { this.setState({ whichComponentToShow: "Screen2" }); }; goToList = () => { this.setState({ whichComponentToShow: "Screen1" }); }; render() { if (this.state.whichComponentToShow === "Screen1") { return ( <div style={{ backgroundColor: "#eee", flex: 1 }}> <h1>home - screen 1</h1> state: <pre>{JSON.stringify(this.state, null, 2)}</pre> <ListHome renderMap={this.goToMap} renderList={this.goToList} /> </div> ); } else { return ( <div style={{ backgroundColor: "pink", flex: 1 }}> <h1>home - screen 2</h1> state: <pre>{JSON.stringify(this.state, null, 2)}</pre> <ListHome renderMap={this.goToMap} renderList={this.goToList} /> </div> ); } } } class ListHome extends React.Component { render() { return ( <div style={{ backgroundColor: "#ddd", flex: 1 }}> <h2>ListHome</h2> ListHome <Slider renderMap={this.props.renderMap} renderList={this.props.renderList} /> </div> ); } } const Slider = (props) => { return ( <div style={{ backgroundColor: "#ccc", flex: 1 }}> <h3>Slider</h3> <button onClick={props.renderMap}>Map</button> <button onClick={props.renderList}>List</button> </div> ); };Puede perforar los accesorios para el componente, he reescrito el código con componentes funcionales. No está probado.
export default function Home() { const [visible, setVisible] = useState(true); const [componentToShow, setComponentToShow] = useState('Screen1'); const goToMap = () => { setComponentToShow('Screen2') } const goToList = () => { setComponentToShow('Screen1') } return( { (whichComponentToShow === 'Screen1') ? ( <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}> <ListHome renderMap = {goToMap} renderList = {goToList} />) :<></> }) export default function ListHome({renderMap, renderList}) { return ( <Slider renderMap= {renderMap} renderList = {renderList} /> ) const Slider = ({renderMap, renderList}) => { // you have them here const [active, setActive] = useState(false) let transformX = useRef(new Animated.Value(0)).current; //animation code I removed that uses the above const and let return ( //code I removed that just creates a button. //The touchable opacity is how I want to use the state. <TouchableOpacity onPress={renderMap}> </TouchableOpacity> ); }