您的位置:首页 > Web前端 > React

react 常见api 使用(长期更新)

2021-05-13 22:48 736 查看

1、父子通信

1.1 父-子 props

父组件:
    class myPage extends React.Component {
           render() {
                return ({/* 子组件   自定义page 是子组件要接受的属性   mypage是要传递的内容*/}我是一个mypage);
      }
}
子组件:
class TabBarComponents extends React.Component {
  constructor(props) {
    // 继承父组件
    super(props);
    this.state = {
    // 接受父组件传的属性
      selectedTab: props.page,
    };
  }
// 然后使用 this.state.selectedTab  这个值, 这个就是mypage   
....
}

1.2

子-》父

子组件:将子组件的value值 text 传递给父组件

    class Input extends Component {
        changeTitle(event) {
            // 子组件调用 父组件通过props传递过来的方法 onChangeText,将要传递的值传进方法
            this.props.onChangeText(event)
        }
        componentDidMount() {
            this.props.getParentTab(1)
        }
        render() {
          return ();
        }    
  }

父组件:

class myPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {newText: 'default'};
  }
  changeText(event) {
    this.setState({
      newText: event.target.value,
    })
  }
    getParentTab = (tab) => {
        console.log(tab)
    }
  render() {
    return (我是一个mypage{this.state.newText}
            {/* 子组件 */});
  }
}

子组件通过调用 props.onChangeText 方法,将值传递进来,父组件通过 changeText 方法来接受 传递进来的值。
套路:子组件通过调用   父组件传递的方法  传值。

父组件调用子组件的方法:

父组件

onRef = (ref) => {
    this.child = ref
  }

addEtcItem = () => {
    this.child.add(); // 调用子组件的方法
  }
....

子组件:

    add = () => {
      // todo
    };

componentDidMount() {

        this.props.onRef(this)

    }

说白了 也是子组件调用父组件的方法,将子组件的this 传递给父组件;
父组件使用this.child  =  ref 接受传进来的 子组件, 这样 父组件就可以使用  this.child.add() 方法了

2、在标签上写样式的方法

{不要扯了,已经到底了!}

3、input type="file"  onchange 获取 e.target

DOM:js:
 uploadFiles = (e) => {
    e.persist(); // 不然e.target 为null
    console.log(e)
    ....

4、create-react-app 打包部署 homepage

package.json

      "homepage": "http://mywebsite.com/relativepath",
      "homepage": "./"  .build/  这个根据具体部署环境定, 一般 取域名即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: