如何从 React Native 中的另一个子组件更新组件

how to update a component from another child component in ReactNative

没错。我已经用谷歌搜索了好几天,但似乎找不到一个有效且我理解的示例。

我目前有三个组件,ButtonComponent、SecondButton 和 TextComponent。

我已经有了它,点击 Button 可以更新状态,从而更改 TextComponent 中的文本(如果我在第 39 行将 setState 设置为文本字符串)。

我怎样才能改变它,让它变成我可以从按钮本身设置的文本字符串,而不是按钮触发的功能,这样 SecondButton 就可以触发与 Button 相同的功能,但更新文字有所不同。

我想这一定是对 onPress 的一个小调整?但我尝试的一切都不断抱怨对象和事物未定义。

谢谢。

import { setStatusBarNetworkActivityIndicatorVisible, StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';


function ButtonComponent({changeText}) {
  console.log(`2. ${changeText} from inside Button Component`)
  return(
    <Button title="change text" onPress={changeText} />
  )

}

function SecondButton({changeText}){
  return(
  <Button title="change text again" onPress={changeText} />
  )
}

function TextComponent({text}) {
  console.log(`3. ${text} from inside Text Component`) //
  return (
    <View>
      <Text style={styles.text}>{text}</Text>
    </View>
  )
}

export default function App() {
console.log('1 .start')

const [text, setText] = useState('default text'); // declared in the screen

const changeText = ({newtext}) => {
    setText(newtext)
    console.log(`4. ${text} just after changeText`)
  }

  return(
   <View style={styles.container}>
     <ButtonComponent changeText={changeText}/>
     <SecondButton changeText={changeText}/>
      <TextComponent text={text}/>
    </View>
  )
}



const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    color: 'red',
  }
});
function SecondButton({changeText}){
  return(
  <Button 
    title="change text again" 
    onPress={() => changeText( { newtext: "different string" })}
  />
  )
}