如何在react native中仅允许inputTextField中的粘贴操作,并从上下文菜单中禁用剪切/复制操作

3okqufwl  于 2023-03-24  发布在  React
关注(0)|答案(1)|浏览(119)

我想在inputTextField中长按文本选择时只允许粘贴操作,但我不想允许剪切和复制操作。有一个属性contextMenuHidden,但它也阻止了粘贴操作沿着复制和剪切。我如何实现这种行为?在chatGPT上搜索显示有两个属性onCopyonCut事件,但我不确定它们是否正确,因为我可以'在官方的docs中找不到这些提及。

wdebmtf2

wdebmtf21#

经过仔细的研究,我发现没有解决这个问题,但有一个黑客的变通办法!
逻辑是每当用户试图选择大小为1到any的文本时,以编程方式将光标设置在端点处。
为类状态中的选择变量添加以下初始化:

constructor(props) {
    super(props);
    this.state = {
      selection: { start: 0, end: 0 },
    };
  }

添加以下helper函数:

handleSelectionChange = (event) => {
    console.log('Selection changed:', event.nativeEvent.selection);
    if (event.nativeEvent.selection.start !== event.nativeEvent.selection.end) { // Checking if cursor's starting and ending point are different, if it is then it implies user selected some text of length 1 or more.
      console.log('text got selected');
      this.setState({ selection: { start: event.nativeEvent.selection.end, end: event.nativeEvent.selection.end } });  //setting cursor at the end point of the text
    }
    else {
      this.setState({ selection: { start: event.nativeEvent.selection.start, end: event.nativeEvent.selection.end } });  //if cursor's starting and ending point are same then leaving it as it is.
    }
  }

在TextInput中添加以下onSelectionChangeselection属性:

<TextInput
  onSelectionChange={this.handleSelectionChange}
  selection={this.state.selection}
/>

然而,这不是一个适当的解决方案,但肯定做的工作!

相关问题