在第二个目标框中显示道具

时间:2017-11-07 18:25:55

标签: javascript react-native

非常 react-native新手。我目前正在尝试用它来弄清楚如何以不同的方式使用它。目前,我试图调用特定抽头对象的道具并将它们发送到输出框。

所以,当你点击艾伦'或者'史蒂夫'他们的名字将出现在红色框中。

我也喜欢深蓝色的背景,一旦点击就变成深红色?

我已经很好地阅读了文档,但我认为我没有得到它,因为它对我来说是新的。我知道我似乎无法访问Component的道具,这显然是Obj类扩展

指导非常感谢。

import React, { Component } from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import style from './style';

class Obj extends Component {
  render(){
    return(
      <TouchableOpacity 
      onPressIn={() => this.setState({tapped: true, tappedName: this.props.plrName})}
      onPressOut={() => this.setState({tapped: false, tappedName: null})}>
        <View style={[style.playerobject, style.shadow]}>
          <Text style={[style.plrobjText]}>{this.props.plrName}</Text>
        </View>
      </TouchableOpacity>
    )
  }
}

export default class App extends Component {
  constructor(props){
    super(props);
    this.state = { 
      tapped: false,
      tappedName: null,
    };
  }
  render() {
    return (

      <View style={[style.main]}>
        <View style={[style.container, this.state.tapped ? {backgroundColor:'darkred'} : {backgroundColor:'darkblue'} ]}>
          <Obj plrName='Alan' />
          <Obj plrName='Steve' />
        </View>
        <View style={style.box }><Text>|{this.state.tapped ? this.state.tappedName : 'x'}|</Text></View>
      </View>
    );
  }
}

'Alan' is currently tapped in this screenshot

1 个答案:

答案 0 :(得分:0)

import React, { Component } from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import style from './style';

class Obj extends Component {

  onPressIn = () => {
    this.props.onPressIn(this.props.plrName)
  }

  onPressOut = () => {
    this.props.onPressOut()
  }

  render() {
    return (
      <TouchableOpacity
        onPressIn={this.onPressIn}
        onPressOut={this.onPressOut}>
        <View style={[style.playerobject, style.shadow]}>
          <Text style={[style.plrobjText]}>{this.props.plrName}</Text>
        </View>
      </TouchableOpacity>
    )
  }
}

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tapped: false,
      tappedName: null,
    };
  }

  onPressIn = (tappedName) => {
    this.setState({ tapped: true, tappedName })
  }

  onPressOut = () => {
    this.setState({ tapped: false, tappedName: null })
  }

  render() {
    return (
      <View style={[style.main]}>
        <View style={[style.container, this.state.tapped ? { backgroundColor: 'darkred' } : { backgroundColor: 'darkblue' }]}>
          <Obj plrName='Alan' onPressIn={this.onPressIn} onPressOut={this.onPressOut} />
          <Obj plrName='Steve' onPressIn={this.onPressIn} onPressOut={this.onPressOut} />
        </View>
        <View style={style.box}><Text>|{this.state.tapped ? this.state.tappedName : 'x'}|</Text></View>
      </View>
    );
  }
}