代码之家  ›  专栏  ›  技术社区  ›  BARNOWL

将angularjs函数转换为react函数

  •  1
  • BARNOWL  · 技术社区  · 7 年前

    我目前正在尝试使用角度功能,但我不能在react应用程序中使用ng-click。

    我正在尝试将下面的函数转换为react函数,我知道 axios ,不知道如何处理react中的叶片变量。

    我需要将角度片段转换为react函数。

    角度(main.js)

    $scope.myfollow = function(user) {
        $http.post('/user/follow/'+ user.id).then(function(result) {
            console.log("user id is:"+ user.id);
        });
    };
    

    反应文件

    render(){
        return(
    
           <div className="followdoe">      
                <button  onClick={ this.btnClick.bind(this) } className={this.state.className}>
                       <p>{ this.state.btnText }</p>
                </button>
           </div>
    
    
        )
    }
    

    route.php路径

    Route::post('user/follow/{id}', 'UserController@my_follow');
    

    profile.blade.php文件

    <div style="margin:30px 0px;">
    
        <button class="follow-button" ng-click="myfollow({{$user}});">+ Follow</button>
    </div>
    

    usercontroller.php用户控制器

        public function my_follow(Request $request, $id)
        {
            $user = auth()->user();
    
            if($user->id != $id && $otherUser = User::find($id)){
    
                $user->toggleFollow($otherUser);
            }
    
        }
       public function getProfile($user)
        {  
            $user = User::with(['posts.likes' => function($query) {
                                $query->whereNull('deleted_at');
                            }, 'follow','follow.follower'])
                          ->where('name','=', $user)->first();
    
    
    
            if(!$user){
                return redirect('404');
            }
    
            return view ('profile')->with('user', $user);
        }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Tholle    7 年前

    您可以在组件上创建一个函数并使用 fetch 应用程序编程接口。

    例子

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          className: "test",
          btnText: "Text",
          user: { id: 123 }
        };
        this.myfollow = this.myfollow.bind(this);
        this.btnClick = this.btnClick.bind(this);
      }
    
      myfollow(user) {
        fetch(`/user/follow/${user.id}`, { method: "POST" })
          .then(response => response.json())
          .then(response => {
            console.log(response);
          });
      };
    
      btnClick() {
        this.myfollow(this.state.user);
      };
    
      render() {
        return (
          <div className="followdoe">
            <button onClick={this.btnClick} className={this.state.className}>
              <p>{this.state.btnText}</p>
            </button>
          </div>
        );
      }
    }