react导航标题右键

IT技术 reactjs react-native react-navigation
2021-05-16 00:51:08

我想在react-native header中添加按钮,该按钮是为了在页面中mas和unmask密码,当我改变状态以改变secureTextEntry值时点击问题,图标不会改变将保留为初始值;该功能工作正常,但图标不能改变

this.state.secureTextEntry ? "eye" : "eye-slash"

这是主要代码

 class ChangePasswordScreen extends Component {
 constructor(props) {
     super(props);
     this.state = {
         newPassword: null,
         currentPassword: null,
         confirmPassword: null,
         errors: [],
         secureTextEntry: true

     };

     this.maskPassword = this.maskPassword.bind(this)
 }
 componentDidMount() {
     this.props.navigation.setParams({
         headerRight: ( < TouchableOpacity onPress = {
                 () => {
                     this.maskPassword();
                 }
             } > < Icon style = {
                 styles.eyeIcon
             }
             name = {
                 this.state.secureTextEntry ? "eye" : "eye-slash"
             }
             size = {
                 20
             }
             color = {
                 Colors.WHITE
             }
             /></TouchableOpacity > )
     })
 }
 static navigationOptions = ({
     navigation
 }) => {
     return {
         // headerTitle: <LogoTitle />,
         headerRight: navigation.state.params && navigation.state.params.headerRight,
     };
 };
 maskPassword = () => {
     this.setState({
         secureTextEntry: !this.state.secureTextEntry
     })

 }

}

3个回答

有点晚了,不过可能会帮助某人。

如果您希望从屏幕本身而不是 App.js 文件向屏幕的标题添加按钮,并且您正在使用功能组件,则如下所示:

import { useNavigation } from '@react-navigation/native'

export default function () {
  const nav = useNavigation();
  useEffect(() => {
    nav.setOptions({
      headerRight: () => <Button />,
    });
  }
}

问题是this.setState不会重新渲染 header 组件。如果您想正确更改标题,则必须再次调用setParams

componentDidMount 中试试这个代码

componentDidMount() {
    this.props.navigation.setParams({
      headerRight: this.setHeaderRight(this.state.secureTextEntry)
    });
  }

设置标题右侧的功能

setHeaderRight = state => {
    //console.log("setHeaderRight", this.state.secureTextEntry);
    return (
      <TouchableOpacity
        onPress={() => {
          this.maskPassword();
        }}
      >
        <Icon
          style={styles.eyeIcon}
          name={state ? "eye" : "eye-slash"}
          size={20}
          color={Colors.WHITE}
        />
      </TouchableOpacity>
    );
  };

状态设置时再次设置标题

maskPassword = () => {
    this.setState({
      secureTextEntry: !this.state.secureTextEntry
    });
    this.props.navigation.setParams({
      headerRight: this.setHeaderRight(!this.state.secureTextEntry)
    });
  };

您将组件设置为组件安装上的导航参数,并在组件安装时传递状态值。

此参数永远不会再次更改或更新,因此导航标题永远不会重新呈现。

更好的方法是将 state 的值直接作为导航参数传递,并在直接在 navigationOptions 中使用的组件中使用它