Làm cách nào để override method của component của React (React-Native)

Hiện tại mình đang có nhu cầu override method _onPress của TextInput để expose sự kiện onPress của nó ra ngoài (Vốn là TextInput không có sự kiện onPress). Nên mình đã thử kế thừa TextInput thế này:

class ExTextInput extends TextInput
{
   _onPress()
  {
     this.props.onPress && this.props.onPress(...arguments); // làm trước vài chuyện gì đó
     super._onPress(...arguments); // gọi lại _onPress gốc, method gốc sẽ trigger sự kiện onFocus
  }
}

Kết quả toàn là _onPress của TextInput chạy chứ không phải _onPress của mình chạy trước :frowning: . Hình như component mà được tạo bằng React.createClass thì không kế thừa kiểu này được.

Mình search google thì toàn ra các bài viết khuyên bảo nên dùng Higher Order Component, Composite over Inheritance các kiểu. Nhưng mình cần handle chính xác sự kiện onPress trước sự kiện onFocus của TextInput (chạy sau là sai mục đích của mình) nên không dùng Composite được.

Mong mọi người giúp đỡ :slight_smile:

1 Like

OK, mình ngồi thử nghiệm cả sáng thì chắc có cách này, nhưng đây không phải là kế thừa :frowning:

var oldGetInitialState = TextInput.prototype.getInitialState;
TextInput.prototype.getInitialState = function() {
  if (this.props.useEx == true) 
  {
     var oldOnPress = this._onPress;
     this._onPress =  function() {
        this.props.onPress && this.props.onPress(...arguments);
        oldOnPress(...arguments);
     }.bind(this);
  }
  if (oldGetInitialState == null) return {};
  else return oldGetInitialState();
}

class Test extend Component
{
    render()
    {
        return 
          <View>
             <TextInput useEx={true} onPress={() => console.log("Yes")}/>
             <TextInput onPress={() => console.log("No")}/>
          </View>;
    }
}

Thử như này có đc ko bạn, mình chưa thử

class ExInput extend Component {
	
	render() {
		return (
		  <TextInput
			{this.props.arg} // Inherit any props passed to it
			onPress={this.props.onPress()}
		  />
		);
	}
}

class Test extend Component
{
	constructor(props) {
		super(props);
		this.onPress = this.onPress.bind(this);
		this.setState {
			arg: [],
		}
	}
	
	onPress() {
		xxx = dosothing;
		this.setState {
			arg: xxx,
		}
	}
	
    render()
    {
        return 
          <View>
             <ExInput arg={this.state.arg} onPress={this.onPress()}/>
          </View>;
    }
}
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?