简体   繁体   中英

Get text from TextView and copy it to clipboard in react native

I want to copy value inside textview by clicking to icon. This is what I've done so far:

  render() {
    return (
        <View style={{marginTop: 50, marginLeft: 50}}>
              <View>
                 <Text>Логин:</Text>
                 <Text ref='myText'>45645546654</Text>    
              </View>
            <TouchableOpacity onPress={() => Clipboard.setString(this.refs.myText.props.children)}>
              <View>
                <MaterialIcons 
                   name='content-copy' 
                   size={21} 
                 />
              </View>
            </TouchableOpacity>
        </View>
    );
  }

Workspace: https://snack.expo.io/@jasurkurbanov/updated2

It is somewhat working on snack. But what when I am running it on my phone I am getting error.

Undefinied is not an object ('evaluating '_this.refs.myText.props.children')

Found answer. The problem was with the constructor. I didn't create it and not defined the state. Please visit https://snack.expo.io/@jasurkurbanov/updated2

You should defined your refs variable on constructor() .

for example:

constructor() {
...
    this.textViewRefs = React.createRef();
...
}

render() {
    return (
...
        <Text ref={this.textViewRefs}>45645546654</Text>
...
    )
}

look this https://reactjs.org/docs/forwarding-refs.html for further information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM