【问题标题】:How can I use properties of elements within other elements in react native?如何在本机反应中使用其他元素中的元素属性?
【发布时间】:2018-03-20 18:55:49
【问题描述】:

也许这是一个愚蠢的问题,如何在其他元素中使用元素的属性? 我想显示他们在不同地方选择的按钮的标题,这是我的代码:

import React, { Component } from 'react';
import { Text, View, StyleSheet, Button, Alert } from 'react-native';
import { Constants } from 'expo';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-elements'; // Version can be specified in package.json

export default class App extends Component {
  _handleButtonPress = () => {
    Alert.alert(
    {Button.title}
    );
  };

  render() {
    return (
      <View style={styles.container}>
      <Text> Whom do you love the most in this world?  </Text>
        <Text style={styles.paragraph}>
          {Button.title}    
        </Text>
      
      <Button
        title="Cat"
        onPress={this._handleButtonPress}
      />
    
        <Button
          title="mother in law"
          onPress={this._handleButtonPress}
        />
        
        
      <Button
        title="dog"
        onPress={this._handleButtonPress}
      />
    
        
      <Button
        title="Computer"
        onPress={this._handleButtonPress}
      />
    
      
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    color: '#34495e',
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

在这种情况下,我希望他们每次选择按钮时,按钮的标题都会出现在不同的部分、警报中、列表中,显示第一个选项和最后一个选项。

[https://snack.expo.io/@julioejurado/-whom-do-you-love-the-most?][1]

【问题讨论】:

  • 不同的地方是什么意思?在下一个屏幕上?
  • 是的不同的地方,我的意思是 {Button.title} 中来自 title = 'foo' 的同一个屏幕

标签: javascript react-native react-proptypes react-props


【解决方案1】:

您可以使用 2 种方法来实现这一点。一种是在组件中或整个应用程序中维护状态,以查看推荐的 Redux 和 React-Redux。

或者您可以在代码中执行以下操作:

<Button title={'Something here'} 
        onPress={() => this._handleButtonPress('Message to show in alert')}/>

在你的处理函数中:

_handlerButtonPress = message => {Alert.alert(message)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2018-01-11
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多